vendredi 27 juillet 2018

if statement in for loop (random number generator

#include <iostream>
#include <cstdlib>
using namespace std;

int main()
{
unsigned seed;
cout << "Input a whole number between 0 and 65535 to\n initialize the random number generator: ";
cin >> seed;
srand(seed);

int number;
number = rand();

int count;
for (count = 1; count <= 20; count++)
{

    if (number >= 1 && number <= 100)
    {
        cout << number << endl;
        number = rand();
    }
    else
    {
        number = rand();
        --count;
    }

}
return 0;
}

I was trying to code a random number generator that prints out 20 random numbers between 1 and 100 including 1 and 100. Everything is working fine now after i decremented "count" in the else statement (--count). without that "--count" the program outputs only one or no numbers at all. Why would it output only one number if the if-statement initializes the rand() function to generate a new number after every loop? Can anyone explain to me why I had to put --count in this else statement? It was more of a guess to decrement "count" than knowing why. Even if it would generate a number over 100 it has to generate it again and again until it fits the case or not?




Aucun commentaire:

Enregistrer un commentaire