[英]sum of two random integers between 1 and 6
public class SumOfTwoDice {
public static void main(String[] args) {
int SIDES = 6;
int a = 1 + (int) (Math.random() * SIDES);
int b = 1 + (int) (Math.random() * SIDES);
int sum = a + b;
System.out.println(sum);
}
}
Here is the above code to find out the sum of two random integers between 1 and 6 or any given number. 这是上面的代码,用于找出1到6之间或任意给定数字之间的两个随机整数之和。
The below is my own written code, Is this fine. 下面是我自己的书面代码,可以吗? The way i am achieving the Sum of Two random integers.
我实现两个随机整数之和的方式。 Is this Correct ???
这是正确的吗 ?
public class TestSample {
public static void main(String[] args) {
int a = Integer.parseInt(args[0]); // 1
int b = Integer.parseInt(args[1]); // 6
double ran = Math.random();
System.out.println("Random Number" + ran);
double random;
if(a < b)
random = (b-a)*ran + a;
else
random = (a-b)*ran + b;
double sum = random + random;
System.out.println("Random Number" +(int)sum);
}
}
You have to use Math.random() again to generate a new random number between 0 and 1. Should be something like this: 您必须再次使用Math.random()来生成一个介于0和1之间的新随机数。应该是这样的:
public class TestSample {
public static void main(String[] args) {
int a = Integer.parseInt(args[0]); // 1
int b = Integer.parseInt(args[1]); // 6
double random1, random2;
if(a < b) {
random1 = (b-a)*Math.random() + a;
random2 = (b-a)*Math.random() + a;
}
else {
random1 = (a-b)*Math.random() + b;
random2 = (a-b)*Math.random() + b;
}
double sum = random1 + random2;
System.out.println("Random Number" +(int)sum);
}
}
No. You are calculating random just once and then doubling the value. 不。您只计算一次随机值,然后将值加倍。 You want to calculate two distinct random numbers.
您要计算两个不同的随机数。
int random1 = a + (int) ( Math.random() * (a-b) );
int random2 = a + (int) ( Math.random() * (a-b) );
int sum = random1 + random2;
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.