生成十进制数,其总和在java中不大于Y.

时间:2012-07-01 14:20:09

标签: java random

我需要生成6个浮点数,其总和在30到36之间 例如,num1 = 4.40,num2 = 6.20,num3 = 5.20,num4 = 5.30,num5 = 4.80,num6 = 4.70

数字必须介于3.50和8之间。

1 个答案:

答案 0 :(得分:0)

这是一个强力解决方案:

import java.util.Random;
public class Solution {

    private static Random random = new Random();
    private static double[] arr = new double[6];

    private static double solve() {
        double sum;
        while (true) {
            sum = 0;
            for (int i = 0; i < 6; i++)
                sum += arr[i] = 3.5 + random.nextDouble() * (8 - 3.5);
            if (sum <= 36 && sum >= 30) break;
        }
                    // 2 decimal places
        for (int i = 0; i < 6; i++) {
            arr[i] = (int)(arr[i] * 100);
            arr[i] /= 100;
        }
        return sum;
    }

    public static void main(String[] args) {
        System.out.println("The sum is " + solve() + "\nNumbers:");
        for (double i : arr)
            System.out.println(i);
    }
}