java - 找到最接近 3 个随机数平均值的数字
问题描述
我需要找到最接近 3 个随机数平均值的数字。
程序将生成和a
,根据这些数字计算平均值,然后告诉我们哪个随机数最接近我们的平均值。
我现在得到了这个:b
c
import java.util.Random;
public class AvgRnd {
public static void main(String[] args) {
Random rnd = new Random();
int a = rnd.nextInt(11);
int b = rnd.nextInt(37)-13;
int c = rnd.nextInt(54)+34;
System.out.println(a+" "+b+" "+ c);
int avg = (a+b+c)/3;
System.out.println(avg);
}
}
解决方案
如果我正确理解你的问题 Math.abs() 就是你要找的。
//example:
//a = 8, b = 7, c = 57 --> avg = 24
int nearest = Math.abs(avg - yourValue);
//this returns the absolute difference to your average value
//in this case int nearest for a would be 16
//and for b nearest = 17
//for c nearest = 33
您只需要比较这些值并获得这三个值中的最小值,这应该是您正在寻找的值。
我希望这是可以理解的,如果不只是再问一次;)
推荐阅读
- python - 将点转换回 3D
- python - Spiral problem, why does my loss increase in this neural network using Keras?
- javascript - 在 Chrome 扩展后台脚本中使用 Sentry 不起作用
- c++ - 如何在另一个文件中定义类外部的类构造函数?
- c - 使用 strlen 计算字符串的大小
- logging - 禁用彩色控制台输出
- python - 如何让我的逻辑回归运行得更快?
- javascript - 每 x 秒刷新一次 DIV,无需重新加载页面
- swift - 在 Int 附加数组中转换字符串(数字) - Swift
- java - 我使用 gRPC 生成 java 代码“@javax.annotation.Generated”,它报告“错误:(20,18)java:找不到符号”。如何解决?