简体   繁体   English

用Java将随机生成的数字加在一起

[英]Adding randomly generated numbers together in Java

I have a problem I'm trying to work on. 我正在尝试解决一个问题。

I have this code so far. 到目前为止,我已经有了这段代码。

public class Average {
        public static void main(String[] args){
            int n= Integer.parseInt(args[0]);
            int i;
            for(i=1; i<= n; i++){
                System.out.println(Math.random());              
            }
        }
    }

This gives me n randomly generated numbers, Yay! 这给了我n个随机生成的数字,是的! But I want to be able to add those numbers together. 但我希望能够将这些数字加在一起。 Can this be done? 能做到吗? I'm completely lost. 我完全迷路了。

public class Average {
    public static void main(String[] args){
        int n= Integer.parseInt(args[0]);
        int i;
        double thisRand = 0;
        double result = 1;
        for(i=1; i<= n; i++){
            thisRand = Math.random();
            System.out.println(thisRand);
            result *= thisRand;
        }
    }
}

The variable result will contain the multiplication of your random values. 可变result将包含您的随机值的乘法。 The *= operator multiplies the the values on either side of it, and stores it in the left-hand side variable. *=运算符将其两侧的值相乘,并将其存储在左侧变量中。

Here is the solution, you will give two arguments, "number" that is the amount of numbers you want to multiply, and the "result" of multiplying all numbers, hope is what you want. 这是解决方案,您将提供两个参数,“ number”是您要相乘的数量,以及“结果”是将所有数字相乘,希望就是您想要的。 I use recursive programming 我使用递归编程

   public static void main(String[] args) {
      Integer result=1;
      System.out.println(multiplyNumbers(3, result));
   }
   static Integer multiplyNumbers(int number, int result){
        int value = new Random().nextInt(10);
        if (number > 0){
            result = multiplyNumbers(--number, result);
            return result *= value;
        }
        return 1;
    }

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM