问题
Here is my code
here I made a loop which is supposed to break when the value of x becomes equal to the random number
public class Bark {
public static void main(String[] args) {
for (double x = 0 ; x>-1 ; x++) {
System.out.print(x + " ");
if( x == Math.random()) {
break;
}
}
}}
回答1:
You loop iterates from 0 to Infinity in increments of 1, and Math.random can only equal a value from 0.0 to less than 1. If the Math.random() does not equal 0 on the first iteration, the loop will go forever.
回答2:
You are generating a new random number each time. To break, better generate random number once, within range, and then loop through.
回答3:
The for counter x starts at 0, and increments every iteration (x++) and continues as long as x is > -1. x is greater than -1 when the loop starts and continues to increase, so is always >-1 so continues forever.
The other check is Math.random, While Math.random does return a number between 0 and 1, it returning a 0 or 1 in the first iteration is very improbable.
回答4:
The condition x>-1 will always be true and the only time when x == Math.random() can be true is in the first iteration and as you can expect, it's the rarest of chances.
回答5:
A few points here:
First, you're generating real numbers, not integers, but you're comparing it to integers. x will always be an integer, and Math.random() will generate a random real value between 0 and 1. (Note that the fact that x is technically of type double doesn't really help because you start at 0 and increment by 1 every time, so it'll always be an integer).
You should look at this Q&A to see how to generate only integers so that there's at least the possibility of it matching on each iteration.
Secondly, other answers have already pointed this out, but Math.random() will generate numbers between 0 and 1, meaning that the only times that this could possibly match are on the first or second iteration.
Third, this might be semantics, but referring to this as "the random number" isn't correct. You're generating a new random number each iteration, so you're actually generating lots of random numbers (not just one).
来源:https://stackoverflow.com/questions/59378409/why-does-this-loop-keep-going-forever