Need help with my code its not stopping once the correct answer is given i don't know why please help...I'm using 25 as the seed and the answer is 62 but my code says 62 is too high ... thank you.

#include <iostream>
#include <cstdlib>
using namespace std;

int testTheGuess(int ,int);

int thinkUpNumber(int);

int main()
{
	int x, guess;

	cout << "Enter a seed for my Number: ";
	cin >> x;
	cout << x << "\n" << "I have a Number between 1 and 100.\n";
	cout << "Can you guess my Number?\n";

	thinkUpNumber(x);

	cout << "Please enter your guess: ";
	cin >> guess;

	testTheGuess(guess, x);

	return 0;
}

int thinkUpNumber( int seed)
{
	int answer;
	
	answer = rand();

	srand(seed);

	rand();

	return answer;
}

int testTheGuess(int guess, int answer)
{
	int count = 0;
	
	while( guess != answer)
	{
		if( guess < answer)
		{
			cout << guess << " is to low.\n Try Again.\n\n";
		}

		else if( guess > answer )
		{
			cout << guess << " is to high.\nTry Again.\n\n";
		}

		else if( guess == answer )
		{
			cout << guess << " is correct.\nYou Must be lucky.\n\n";
		}

		else 
		{
			cout << "Invaild input please try again\n";
		}

		cout << "please input another guess: ";
		
		cin >> guess;

		count++;
	}

	if( count < 10)
	{
		cout << "Good Job it only took you " << count << " times.\n\n";
	}
	
	else if( count > 10)
	{
		cout << "Uh oh took you " << count << " times.\n\n";
	}
	else 
	{
		cout << "WOW";
	}

	return 0;
}

Recommended Answers

All 2 Replies

You have to seed rand() with a value that changes, and your following sentence on line 36 has no effect:

rand();

you can try something like this to pick a random number between 1 and 100:

srand(time(0));
int answer=rand()%100+1;

and then let the user guess a number and check it:

int guess;
cout << "Guess a number: ";
cin >> guess;
cin.ignore();

if(guess==answer) cout << "Excellent, You got it !!!";
else cout << "Wrong number, the right answer is " << answer;

Move line 32 to between line 14 and 15. Only call srand() once per program. Call srand() before any calls to rand(). Declare the variable answer in main() and pass it to thinkUpNumber() by rerence or store the return value of thinkUpNumber() in answer.

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.