简体   繁体   中英

for loop will not iterate up to the required number each time

I'm just working through some beginner Java questions, and here is one where I am to output the result of 10 randomly generated 'coin tosses' (using Math.random()).

For some reason, the program will not iterate all the way to 10. Sometimes it will output 5 results, or 7, or 8 etc. etc.

Is there a reason for why the iterations aren't always constant?

public class Coin
{
  public static void main(String[] args)
  {
    for (int i=0; i<11; i++)
    {
      if (Math.random() < 0.5)
      {
        System.out.println("H");
      }
      else if (Math.random() > 0.5)
      {
        System.out.println("T");
      }
    }
  }
}

The problem comes from the fact that you are recalculating a random variable each time when you should be storing the result.

Your code commented:

if (Math.random() < 0.5) { // if the random value is less than 0.5
    System.out.println("H");
} else if (Math.random() > 0.5) { //otherwise, it the new random value is greater than 0.5
    System.out.println("T");
}

This can be corrected with:

double random = Math.random();
if (random < 0.5) {
    System.out.println("H");
} else { // if it is not "< 0.5", then surely it is "> 0.5" (can't be equal to 0.5)
    System.out.println("T");
}

Side note, you will loop 11 times, not 10 times, because there are 11 numbers between 0 and 10 inclusive.

Side note 2: it would be better not to use Math.random() here but use Random.nextBoolean() , which gives directly a random boolean value.

You don't need the second if - at the moment, in each iteration if you don't print "H" , you're tossing a second coin, and only printing "T" if the second coin is a tail.

Should be just:

  if (Math.random() < 0.5)
  {
    System.out.println("H");
  }
  else
  {
    System.out.println("T");
  }

With your original code, the chances of a head first time are 50/50, in which case you print "H" . If you didn't toss a "H" (ie the other 50% of the time), you now only have a 50/50 chance of printing a "T" , so you'll only see "T" 25% of the time.

So on average, you'll be seeing 7.5 results, 5 of which will be "H" and 2.5 of which will be "T" . Oh, except that you're doing the loop 11 times, so multiple that by 1.1

As the first line of the for loop, just above the first if , put:

System.out.println("This is iteration #" + i);

So you really see the "code in motion", and you can differentiate between the number of times the loop is actually iterating, versus the unpredictable nature of the loop body, where output is conditional on pseudo-random input.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM