首页 > 解决方案 > 找到最接近 3 个随机数平均值的数字

问题描述

我需要找到最接近 3 个随机数平均值的数字。
程序将生成和a,根据这些数字计算平均值,然后告诉我们哪个随机数最接近我们的平均值。 我现在得到了这个:bc

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);
}
}

标签: javarandomaverage

解决方案


如果我正确理解你的问题 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

您只需要比较这些值并获得这三个值中的最小值,这应该是您正在寻找的值。

我希望这是可以理解的,如果不只是再问一次;)


推荐阅读