954,535 Members — Technology Publication meets Social Media
Username:
Password:
Lost login information?
Have something to say? Contribute New Article Reply to this Article

C++ Random Numbers

Hi, I'm new to this C++ stuff. So if anyone can help that would be nice. I have this program to generate a random number and a the user inputs a number from the keyboard to correctly guess the number that the computer randomly chooses. but the numbers are always changing each time, which makes it hard to correctly guess the correct number. So the question is, is it possible to randomly choose a number without it changing each iteration?

#include
#include
#include
#include
using namespace std;

int main ( )
{
int guess;
char ans;

srand (time (0));
for (int i = 0; i < 100; i++)
{
int random = rand( );
int num = ((random % 100) + 1);

cout << "Guess a number between 1 and 100: ";
cin >> guess;

if (guess > num)
{
cout << "The number is lower. Try Again!!\n\n";
continue;

}
if (guess < num)
{
cout << "The number is higher. Try Again!!\n\n";
continue;


}
else if (guess = num)
{
cout << "You've guessed correctly!\n\n";
break;
}

}

return 0;
}

Duke_0064
Newbie Poster
6 posts since Mar 2006
Reputation Points: 10
Solved Threads: 0
 
else if (guess = num)


should be:

else if (guess == num)
Clinton Portis
Practically a Posting Shark
833 posts since Oct 2005
Reputation Points: 237
Solved Threads: 118
 
Hi, I'm new to this C++ stuff. So if anyone can help that would be nice. I have this program to generate a random number and a the user inputs a number from the keyboard to correctly guess the number that the computer randomly chooses. but the numbers are always changing each time, which makes it hard to correctly guess the correct number. So the question is, is it possible to randomly choose a number without it changing each iteration?


Wrap your code in "Code Tags" - makes it easier for everyone to read. :)

Aside from Clinton's excellent spot, there is a slight flaw in your logic...

//Snipped #include's
int main ( )
{
	int guess;
	char ans;
	
	srand (time (0));
    for (int i = 0; i < 100; i++)
	{


So... everything after this curly brace (up til the closing brace) gets repeated 100 times.. including:

int random = rand( );
	    int num = ((random % 100) + 1);


I suggest putting these 2 lines before your loop starts, then you will only be selecting your random number once.


Also, this kind of "guessing game" would look much cleaner if you could saydo....while(guess!=num) instead of for...

Bench
Posting Pro
577 posts since Feb 2006
Reputation Points: 307
Solved Threads: 63
 

Thanks guys!!

Duke_0064
Newbie Poster
6 posts since Mar 2006
Reputation Points: 10
Solved Threads: 0
 

This question has already been solved

Post: Markdown Syntax: Formatting Help
You