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 <iostream>
#include <cstdlib>
#include <cmath>
#include <ctime>
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;
}

Edited 3 Years Ago by happygeek: fixed formatting

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 say do....while(guess!=num) instead of for...

This question has already been answered. Start a new discussion instead.