随机数加总数

时间:2013-04-08 11:58:29

标签: java generator

大家好,我对这段代码感到有点困惑。除了我希望随机数加起来以用户定义的数量之外,我已经全力以赴。例如,用户输入23500我希望所有随机数加起来总数。 这就是我到目前为止所拥有的

package containerweights;
import java.util.Random;
import java.util.Scanner;
import java.io.*;
public class Containerweightgenerator {

    /**
     * @param args
     * @throws Exception 
     */
    public static void main(String[] args) throws Exception {
        // TODO Auto-generated method stub

        Scanner input = new Scanner(System.in);
        System.out.printf ("%n ***Random Number Genreator*** %n%n");
        System.out.print("Enter total: ");
        double total_weight = input.nextDouble();
        System.out.print("Enter amount: ");
        double total_pallets = input.nextDouble();

        double average_weight = total_weight / total_pallets;
        System.out.printf("%-40s -%10.2f%n", "Average Weight is: ", average_weight);

        double first_weight = average_weight - 50;
        double second_weight = average_weight + 50;

        double START = first_weight;
        double END = second_weight;
        Random random = new Random();
        for (int idx = 1; idx <= total_pallets; ++idx)
        {
            showRandomInteger(START, END, random);
        }
        }
    private static void showRandomInteger(double sTART, double eND, Random aRandom) throws Exception{
        if ( sTART > eND )
        {
            throw new Exception(" Start connot exceed End.");
        }
        long range = (long)eND - (long)sTART + 1;

        long fraction = (long)(range * aRandom.nextDouble());
        int randomNumber = (int)(fraction + sTART);
        System.out.println(randomNumber);
    } 
        private static void log(String aMessage)
        {
            log(aMessage);
        }   
    }

2 个答案:

答案 0 :(得分:4)

只是给出随机数字。如果您提供的最后一个数字超过总数,而不是该数字返回与总数

的差异

根据新要求,我编辑了以下答案:

int pallets=10;
int targetWeight=100;
int totalSoFar = 0;
int[] palletWeight = new int[pallets];

//Give random weight to N-1 pallets
for (int i=0; i<pallets-1; ++i){
    palletWeight[i] = random.nextInt(1.33 * targetWeight / pallets);
    totalSoFar += palletWeight[i];
}

//Check if we exceeded our target
if (totalSoFar > targetWeight){    
    while(totalSoFar > targetWeight){
      int x = random.nextInt(pallets - 1); //pick a pallet at random
      int a = random.nextInt(palletWeight[x]);
      palletWeight[x] -= a; //take of a random 'a' grams out of its weight
      totalSoFar -= a;
    }
}
//Now we are under the target weight, let the last pallet be the difference
 palletWeight[pallets-1] = targetWeight - totalSoFar;

答案 1 :(得分:1)

如果Lefteris的回答对您不起作用(因为可能要求所有值实际上都是“随机” - 撇开这意味着什么),您唯一的选择就是重复生成随机数集和求和他们了。

那是丑陋而缓慢的,我更喜欢Lefteris的回答。但他的确意味着系列中的最后一个数字不会是随机的,它的大小分布可能会让它脱颖而出。