I am trying to generate pseudo random ints using the rand()
function. It works, but my problem is that it is always "selecting" the same name for the int. (In this case, it is 41. I think if you put the rand()
in the while loop of main it is 85 or something.)
Is there a way to fix this? Here is my code:
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
int guess;
int danse = rand() % 101;
using namespace std;
void more(){
cout << "The number that you need to guess is higher!";
return;
}
void lower(){
cout << "The number that you need to guess is lower!";
return;
}
int main(){
while(1){
cout << "\nGuess a number 0-100: ";
cin >> guess;
if (guess > danse){
lower();
}
if (guess < danse){
more();
}
if (guess == 101){
break;
}
if (guess == danse){
cout << "\nYOU GUESSED IT. ARE YOU A WIZARD?! BECAUSE THAT IS PRETTY NEAT.";
break;
}
}
}
Just a few side notes: Please don't try and tell me things I already know, like, explaining why I am using void functions, with return. Please, also do not try to convince me that using namespace std; is the "bad" way to do it. I understand that there are other ways of doing it. I choose not to.
Thanks!
You need to seed the random number generator by calling srand once before using rand
. The current time is a cheap and easy way to choose a seed that varies between runs of your program.
int danse;
int main(){
srand(time(NULL));
danse = rand() % 101;
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments