简体   繁体   English

两者产生随机数,且乘积不同

[英]The two generate random numbers and their product is different

So im creating a program that generate 2 random numbers and need to multiply them: 因此,即时通讯创建了一个程序,该程序生成2个随机数并需要将它们相乘:

public static  int thenumber(){
int number1=(int)(Math.random()*10+1);


return number1;
}
public static  int thenumber2(){
int number2=(int)(Math.random()*10+1);
return number2;
}

and solve it in : 并解决它:

public static int thefusion(){
int demi =thenumber() * thenumber2();
return demi;
}

My problem is when i run it the product of two number is Different ex: 7 * 4 = 24 我的问题是,当我运行它时,两个数的乘积是不同的ex:7 * 4 = 24

A complete code example would be nice (see How to create a Minimal, Complete, and Verifiable example ), but let me guess: You are first seeing the two random numbers (from printing them or some other way). 完整的代码示例将很不错(请参见如何创建最小,完整和可验证的示例 ),但让我猜测:您首先看到了两个随机数(通过打印它们或以其他方式)。 Then you call your method. 然后调用您的方法。 The method draws two new random numbers from thenumber() and thenumber2() . 该方法从thenumber()thenumber2()绘制两个新的随机数。 That's the point in (pseudo-)random numbers, you don't the same number each time. 这就是(伪)随机数的意义,您每次都使用不同的数字。 So if you drew the numbers 7 and 4 the first time, maybe next time you get 3 and 8, so the product is 24. 因此,如果您是第一次绘制数字7和4,也许下次是3和8,那么乘积就是24。

There are a couple of possible solutions: 有两种可能的解决方案:

  1. When calling thenumber() and thenumber2() , assign the results to two variables. 调用thenumber()thenumber2() ,将结果分配给两个变量。 Now you can see which numbers you got. 现在,您可以查看获得的号码。 Pass those two numbers into your thefusion method, and it should calculate the expected product. 将这两个数字传递到您的thefusion方法中,它应该计算出预期的乘积。
  2. Rather than Math.random() use the Random class and instantiate it with a known seed. 而不是Math.random()使用Random类并用一个已知的种子实例化它。 Draw the two numbers from it and inspect them. 从中画出两个数字并检查它们。 Make a new Random instance from the same seed and have thefusion() use it. 从相同的种子中创建一个新的Random实例,并让thefusion()使用它。 Now it will draw the same two numbers, and you will get the product you expected. 现在它将绘制相同的两个数字,您将获得所需的产品。

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

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