Click here to Skip to main content
15,886,518 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
This does not work properly please check for alterations .Refer below as i have entered the code.

What I have tried:

C++
<pre>
#include <iostream>
#include <ctime>
#include <cstdlib>
using namespace std;

int main()
{
	srand(time(NULL));

	int tries = 0;
	int iNum;
	int UpperLim = 100;
	int LowerLim = 10;
	int iCompNum;


	cout << "Enter a number: ";
	cin >> iNum;

	do
	{
		iCompNum = rand() % (UpperLim - LowerLim) + LowerLim;

		cout << "\nComputer's guess(" << 10 - tries << " tries left): ";
		cout << iCompNum;
		++tries;

		if (iNum > iCompNum)
		{
			cout << "\nThe number is less than the entered..!(" << 10 - tries << " tries left)\n\n";
			LowerLim = iCompNum+1;
		}
		else if (iNum < iCompNum)
		{
			cout << "\nThe number is greater than the entered..!(" << 10 - tries << " tries left)\n\n";
			UpperLim = iCompNum-1;
		}
		else if (iNum == iCompNum)
		{
			cout << "\nYou got my number!!!\n\nYou guessed the number in just " << tries << " tries!\n\n";
		}
		else if (tries >= 10)
		 {
			cout << "You Lose!Correct Answer is:" << iNum << endl;
}
	} while (iNum != iCompNum);
	

	return 0;
}
Posted
Updated 28-Mar-20 6:03am
Comments
k5054 28-Mar-20 11:52am    
In what way does this "not work properly"?
Dilshan De Silva (Dippi) 28-Mar-20 12:15pm    
Hi thank you for taking your time. So when the program runs out of tries it doesnt output the comment "You Lose!Correct Answer is:".
Richard MacCutchan 28-Mar-20 11:55am    
"This does not work properly"
What does that mean? Perhaps the fact that the computer is doing the guessing but you are telling the user that they win or lose.
Dilshan De Silva (Dippi) 28-Mar-20 12:14pm    
Hi thank you for taking your time. So when the program runs out of tries it doesnt output the comment "You Lose!Correct Answer is:".
Richard MacCutchan 28-Mar-20 12:19pm    
See below.

1 solution

The problem is at the end of the loop. If you run out of tries then you need to use a break statement to get out of the loop. And after exiting the loop you should print the fail or success message, depending on whether iNum and iCompNum are equal or not. So change it to:

C++
        else if (tries >= 10)
        {
             break;
        }
    } while (iNum != iCompNum);
    if (iNum == iCompNum)
    {
        cout << "You Lose! Correct Answer is:" << iNum << endl;
    }
    else
    {
        cout << "You win, I cannot find it" << endl;
    }
    
    return 0;
}
 
Share this answer
 
Comments
Dilshan De Silva (Dippi) 28-Mar-20 12:27pm    
Thank You for the help
Richard MacCutchan 28-Mar-20 13:08pm    
You are welcome.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900