0

Given below is my attempt to create a simple high-low game. I just don't understand why the code given below behaves differently when I place the srand(time(0)) inside the do-while loop, i.e, why does the modified code generate the same random number in each iteration of the loop?

#include<iostream>
#include<cstdlib>
#include<ctime>

int main(){
    int c;
    srand(time(0));
    do{
        int i, num;
        int min = 1;
        int max = 10;
        float fraction = 1.0 / (RAND_MAX+ 1); 
        num = min + (max-min + 1) * (rand() * fraction);
        for (int j=0;j<20;j++){
            std::cout<<"*";

        }
        std::cout<<"THE GUESSING GAME!";
        for (int j=0;j<20;j++){
            std::cout<<"*";

        }

        std::cout<<"\nRange of guess should be 1 to 10 inclusive\n ";
        std::cout<<"Guess a number: ";
        std::cin>>i;

        while(1){
            if (i==num){
                std::cout<<"Yeah! you guessed it right! "<<i<<" is the right number "<<std::endl;
                break;
            }else if (i<num){
                std::cout<<"Too low\n";
                std::cout<<"Guess another number: ";
                std::cin>>i;

            }else{
                std::cout<<"Too high\n";
                std::cout<<"Guess another number: ";
                std::cin>>i;

            }

        }

        std::cout<<"\nWanna play again? Press 1 to continue and 0 to exit: ";
        std::cin>>c;
    }while(c);
        return 0;
}
mirror06
  • 63
  • 1
  • 7
  • Because your loop will run many times in the single second. Now, go and read the manual page for `srand()`, and you should be able to figure it out all by yourself. – Sam Varshavchik Mar 25 '18 at 18:04
  • If you reset the seed every time in a loop, the value returned by `time(nullptr)` will likely be the same since it returns the number of seconds since the Unix epoch and your loop runs a lot of iterations during a second. Same seed = same random number. – eesiraed Mar 25 '18 at 18:04
  • 1
    Have a look at the page on [minimal complete examples](https://stackoverflow.com/help/mcve). It's not just to make our jobs easier, it's to give you the ability to reveal bugs in your own code. – Beta Mar 25 '18 at 18:05
  • 1
    Prefer the stuff in the `` header over crappy `srand`/`rand`. – Jesper Juhl Mar 25 '18 at 18:12

0 Answers0