Good day, dear programmers. I am a first-year student (3rd beginning of classes) in the specialty Software Engineering. Before studying, I decided to practice a little with a friend in C ++ and a question arose.

I describe the essence: We want to make a game in which a random number will be selected from 1 to 100 and 5 attempts will be given (for example) to guess the number. Everything turned out for us (even the cases, although it looks like a govnokod), except for the correct randomization. The number when restarting the program remains the same. I can provide the code, although I think that here everything is clear.

#include <iostream> #include <Windows.h> #include <conio.h> #include <cmath> #include <string> using namespace std; int main(int argc, char *argv[]){ int x, correct, attempts; correct = rand()%100+1; attempts = 15; string padej; cout << "Zdarova! Nachinaem igry\n\n"; start: if (attempts <= 15 && attempts >= 5) { padej = " popytok"; } if (attempts <=4 && attempts >=2) { padej = " popytki"; } if (attempts == 1) { padej = " popytka"; } if (attempts == 0) { cout << "You've lost"; Sleep(5000); return 0; } cout << "U vas " << attempts << padej << " \n\n"; cin >> x; if(x == correct){ cout << "Otvet verniy" << endl; system ("PAUSE"); return 0; } else if(x > correct && x<=100){ cout << "Visoko!\n\n"; attempts--; goto start; } else if(x < correct && x >= 1) { cout << "Nizko!\n\n"; attempts--; goto start; } else{ cerr << "Neopoznannoe chislo\n\n"; goto start; } getch(); } 

1 answer 1

In all languages ​​known to me, before using rand, a timer must be initiated. Google prompts , ( The first link ) that in c ++ it is done like this

 srand ( time(NULL) ); 
  • 3
    Only this is not a timer, but a rand seed. The initial element of the sequence for generating random numbers (for example, by the linear congruent method). It is sometimes useful to output it to the log, which would then repeat the behavior of the game, indicating the same seed. - IronVbif
  • And it’s worth remembering that all program launches within the same second will work with the same rand () sequence. For programs launched by hands, this usually does not matter, but in a loop from a script ... - avp
  • And, in principle, it is even possible to do without generating a random sequence of grain, if it is not particularly important to have an “exclusive” sequence every time after the new launch of the program. - Salivan