问题
For some reason this line of code int u=(int)Math.random()*6 + 1; will only return a 1 as a result.
I found out that its just skipping the whole (int)Math.random()*6 and is only using the 1 as when I changed it to 2 it only returned 2.
Anyone know What's happening?
回答1:
The cast of Math.random() to int is occurring before the multiplication by 6. The cast operator is of higher precedence than *.
The Math.random() method returns a random number between 0 (inclusive) and 1 (exclusive), so the cast always returns 0.
To provide the proper range, multiply Math.random() before the cast by inserting parentheses. The range of Math.random() * 6 is 0 (inclusive) to 6 (exclusive).
int u = (int) (Math.random()*6) + 1;
回答2:
What is happening:
Math.random()Returns a double value with a positive sign, greater than or equal to 0.0 and less than 1.0.(int)Math.random()cost the double value to0, since type cast has a higher priority compared with*.(int)Math.random()*6always is0,you get what you have.
来源:https://stackoverflow.com/questions/53771414/expression-with-math-random-always-returns-the-same-value