开发者

sum of two random integers between 1 and 6

开发者 https://www.devze.com 2023-04-05 07:49 出处:网络
public class SumOfTwoDice { public static void main(String[] args) { int SIDES = 6; int a = 1 + (int) (Math.random() * SIDES);
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.

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);
    }
}


Mandatory XKCD:

sum of two random integers between 1 and 6


You have to use Math.random() again to generate a new random number between 0 and 1. Should be something like this:

 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;
0

精彩评论

暂无评论...
验证码 换一张
取 消