ive just started programming today, and i am working on making a simple number guessing game where you have 10 tries to guess a number and it gives a response based on if you get the number the first try, get it right before the ten tries are up, guess too high, guess too low, or if you dont guess the number in the allotted turns. My problem is that the random number algorithm always gives the same numbers in the same order, so if you restart it after you have played it before, the answers are always the same. My question is, is there any way to fix the code so that it generates a new random number every time it is ran so that is re-playable?
#include <iostream>
#include <string>
usingnamespace std;
int main()
{
int a,b,c,d,e,f;
string str1, str2, str3;
e = 1;
while (e == 1)
{
a = 0;
f = 0;
string str2 = "yes";
string str3 = "no";
for(c = 4; c <=100; c++)
{
a = (rand() % 100) +1;
}
d = 11;
while (d > 0)
{
d = d-1;
if (d == 10)
{
cout << "Try to guess the number in under 10 tries: ";
cin >> b;
}
elseif ( (d == 9) && (b == a))
{
cout << "WOW!!! .__. You managed to get it on the first try!! That's AMAZING!!!!!!!" << endl;
d = 0;
}
elseif ( (d < 10) && (b < a))
{
cout << "Your guess was too low, why don't you guess again? ";
cin >> b;
}
elseif ( (d < 10) && (b > a))
{
cout << "Your guess was too high, why don't you guess again? ";
cin >> b;
}
elseif ( (d < 10) && (b == a))
{
cout << "CONGRATULATIONS!!! You finally got it! ^_^" << endl;
d = 0;
}
}
if (b != a)
{
cout << "Well, I'm sorry. You didn't manage to guess it. Was this your first time playing?";
}
while (f != 1)
{
cout << "Would you like to play again? (yes/no) ";
cin >> str1;
if (str1.compare(str2) == 0)
{
e = 1;
f = 1;
}
elseif (str1.compare(str3) == 0)
{
e = 2;
f = 1;
}
else
{
cout << "WOW! You really are stupid. -_- You can't even type yes or no....\nGo fall in a hole you waste of space!!\n";
}
}
}
}
You need to seed your random number generator using the srand() function so that it comes up with a more random result. My book suggests seeding it with the time() function. Here's what you need to do:
add: #include <time.h>
add: srand((unsigned)time(NULL)); (before you call rand();)