math.random always give 0 result

前端 未结 8 800
伪装坚强ぢ
伪装坚强ぢ 2021-01-29 16:40

I am using Ubuntu 14.04.3 LTS and I am studying Java from the book. I tried to follow one example on the book with Ubuntu Terminal and I\'m using Sublime Text. Here is the code

相关标签:
8条回答
  • 2021-01-29 17:09
    Math.random();
    

    Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.

    This is the problem. You need to then multiply with 10, so you get a number between 0 and 10 and after that you can cast to int.

    0 讨论(0)
  • 2021-01-29 17:13

    The Math.random() method returns a random double that is from 0 (inclusive) to 1 (exclusive). Performing % 10 doesn't affect this value, but casting it to an int truncates any decimal portion, always yielding 0.

    If you want a random number from 0-9, you can multiply Math.random() by 10, instead of taking the remainder when divided by 10.

    Alternatively, you can create a java.util.Random object and call nextInt(10).

    0 讨论(0)
  • 2021-01-29 17:17

    public static double random()

    Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0. Returned values are chosen pseudorandomly with (approximately) uniform distribution from that range.

    (source)

    It returns a double that satisfies 0.0 <= double < 1.0, therefore taking the modulo will always result in zero. I recommend the java.util.Random class to achieve what you need. Specifically Random.nextInt(int).

    0 讨论(0)
  • 2021-01-29 17:18

    Math.random() returns a double value between 0 (inclusive) and 1 (exclusive). It does not return an integer value. Therefore, when you take the number produced by Math.random() modulo 10, it returns the same double value. The final cast to int makes that value always 0.

    Run the following code to see for yourself:

    double random = Math.random();
    System.out.println(random); // for example 0.5486395326203879
    System.out.println(random % 10); // still 0.5486395326203879
    System.out.println((int) (random % 10)); // outputs 0
    

    What you really want is to use a Random object and use Random.nextInt(bound). To have a random integer between 0 and 9, you can use:

    Random random = new Random();
    int value = random.nextInt(10);
    
    0 讨论(0)
  • 2021-01-29 17:18

    Math.random gives a double value between 0 (incl.)-1 (excl.)!

    0 讨论(0)
  • 2021-01-29 17:19

    The Math.random() method returns a Double value between 0 and 1, so you will never get a number greater or equal than 1, you will ever get a value that could be 0, but never 1. And as you are taking the residual from this value over 10, you will ever get a 0 as result.

    Math.random() % 10 will always be 0, because the random method gives you 0 <= value < 1, and when the % 10 operation takes place, you will get 0.

    Check here for more details (oracle documentation)

    0 讨论(0)
提交回复
热议问题