Hello Everyone! This is my first actual post although I've been a member for almost a year. I'm writing a program that will create a random number between 1-1000 and ask the user to guess the random number. I also have the program display an error message to tell the user if the number they guessed was to high or to low. My problem lies here, If the random number picked is 724, and the user guesses 720, the program displays "You are correct the number is 724", when in all reality they are not correct. Another example is if the random number is 906, and you enter 910, it's wrong but if you enter 90x (x = any number, where x != 6) you get the congratulations message. I guess it's only to 2 sig figs and I dont know how to fix that. Thanks in advance. Heres the code:

#include <stdio.h>
#include <iostream>
#include <ctime>
using namespace std;

int main (int argc, char *argv[], char **env)
{
	int guess, randomNum;
	unsigned seed;

	seed = time(0);
	srand(seed);

	randomNum = rand() % 1001;

	cout << "\nPlease enter your guess: ";
	cin >> guess;


	if (guess != rand())
	{
			while (guess < randomNum)
			{
			cout << "\nToo Low.  Re-enter: ";
			cin >> guess;
			}

			while (guess > randomNum)
			{
			cout << "\nToo High. Re-enter: ";
			cin >> guess;
			}
		
			
	}
		else (guess == randomNum);
		
			cout << "\nYou Are Correct!!  The Number was " << randomNum << ".";
			cout << "  Thank You for playing the guessing game.\nGoodbye.\n\n\a";
		
			return 0;

}

Recommended Answers

All 2 Replies

Your RNG mod is wrong.
1 to 1000 thus 0 to 999

randomNum = 1 +(rand() % 1000);

your test is not with your drawn random number!

//if (guess != rand())
if (guess != randomNum)

Rework your code. Use one input point. Do while loop works.

First, please learn how to use code tags when posting to this board. See the announcements at the top to board to learn how to do this.

Second, rand() in this line:

if (guess != rand())

should be randNum.

Third, I think it would be better with a while loop and a series of if elses in it.

while(guess != randomNum)
{
    if(guess < randomNum)
      //do dah
    else
      //do dat
}

But even better would be:

bool controlFlag = true;
while(controlFlag)
{
   if(abs(guess - randNum) < whatever)
     //guess equals randNum
     //set controlFlag to false
   if(guess < randomNum)
     //do dah
   else if(guess > randNum)
     //do dat
}
Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.