-6

I need to generate 6 float numbers whose sum will be between 30 and 36.
For example, num1 = 4.40, num2 = 6.20, num3 = 5.20, num4 = 5.30, num5 = 4.80, num6 = 4.70

The numbers must be in a range between 3.50 and 8.

Avery
  • 2,270
  • 4
  • 33
  • 35
user1494324
  • 21
  • 1
  • 7

1 Answers1

0

Here is a brute-force solution:

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);
    }
}
  • there was error here public static void main(String[] args) { boolean yes = false; while (true) { if (rec(0)) // non-static method rec(int) cannot be referenced from a static context{ break; } } for (double i : arr) // non static variable arr cannot be referenced from a static context { System.out.println(i); } } – user1494324 Jul 01 '12 at 14:43
  • @user1494324 what is it? –  Jul 01 '12 at 14:43
  • @user1494324 Try out this one. –  Jul 01 '12 at 14:49
  • it works but i need numbers with 2 decimal places now the result is 6.23127557775192 4.451141390194612 4.328741839484366 6.501755845303297 6.497070552410639 4.001708360226619 i need to be like in the question example – user1494324 Jul 01 '12 at 14:53
  • 1
    @user1494324 round them. – Kevin Jul 01 '12 at 14:55