Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Problems Generating A Math.random Number, Either 0 or 1

Tags:

java

random

I want a random number, either 0 or 1 and then that will be returned to main() as in my code below.

import java.util.Scanner;
public class Exercise8Lab7 {
    public static void main(String[] args) {

        Scanner input = new Scanner(System.in);

        int numFlips = 0;
        int heads = 0;
        int tails = 0;
        String answer;


        System.out.print("Please Enter The Number Of Coin Tosses You Want: ");
        numFlips = input.nextInt();

        for(int x = 1;x <= numFlips; x++){
            if(coinToss() == 1){
                answer = "Tails";
                tails++;
            }
            else{
                answer = "Heads";
                heads++;
            }
            System.out.print("\nCoin Toss " + x + ": " + answer);
        }
        System.out.println("\n\n====== Overall Results ======" +
        "\nPercentage Of Heads: " + (heads/numFlips)*100 + "\nPercentage Of Tails: " + (tails/numFlips)*100);
    }

    public static int coinToss(){
        double rAsFloat = 1 * (2 + Math.random( ) );
        int r = (int)rAsFloat;
        return r;
    }
}

Many solutions had been suggested to use the util.Random option which I have done and works perfectly but I want to sort out why I can't get this to work. Obviously I want the number to be an int myself so I convert it to an int after the random number has been generated. But no matter what I add or multiply the Math.random() by, it will always all either be Heads or all either be Tails. Never mixed.

like image 604
alannm37 Avatar asked Feb 09 '15 00:02

alannm37


People also ask

How do you generate a random number between 0 and 1?

The rand( ) function generates random numbers between 0 and 1 that are distributed uniformly (all numbers are equally probable). If you attempt the extra credit, you likely will need to use the rand( ) function. If you want to generate random numbers from 0 to 10, you multiply the random number by 10.

Can math random generate 1?

The Math. random() method returns a random number from 0 (inclusive) up to but not including 1 (exclusive).

Which method is used to generate random numbers using math?

random() method returns a pseudorandom double type number greater than or equal to 0.0 and less than 1.0. .

How do you generate a random integer 0 or 1 in Python?

The random() function allows us to generate random numbers between 0 and 1 (generates floating-point random numbers). It is a default random generator function. The uniform() function generates random numbers between specified ranges rather than 0 and 1 (generates floating-point random numbers).


1 Answers

Try this) It will generate number 0 or 1

 Math.round( Math.random() )  ;
like image 115
DzenDzimon Avatar answered Nov 15 '22 22:11

DzenDzimon