简体   繁体   中英

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:

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

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() . 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.

There are a couple of possible solutions:

  1. When calling thenumber() and thenumber2() , assign the results to two variables. Now you can see which numbers you got. Pass those two numbers into your thefusion method, and it should calculate the expected product.
  2. Rather than Math.random() use the Random class and instantiate it with a known seed. Draw the two numbers from it and inspect them. Make a new Random instance from the same seed and have thefusion() use it. Now it will draw the same two numbers, and you will get the product you expected.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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