Guessing number project.

The project works fine with small increment but it exits immediately when guessing from 45 to a large number like 900. why does it do that?


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
#include "pch.h"
#include <iostream>

using namespace std;

int main()
{
	//declaring variables
	int Num1,Input,Tries;

	//initialise variables
	Num1 = 50;
	Tries = 0;
	cout << "Please enter a number: ";
	cin >> Input;

	while (Input > Num1)
	{
		Tries++;
		cout << "Try a smaller number." << endl;
		cout << "Please enter a number: ";
		cin >> Input;
	}
	while (Input < Num1)
	{
		Tries++;
		cout << "Try a larger number." << endl;
		cout << "Please enter a number: ";
		cin >> Input;
	}
	if (Input == Num1)
	{
		Tries++;
		cout << "Yes you are correct. You have guessed " << Tries << " times" << endl;
	}
	return 0;
}
Your code has a logical error in it.

If the number input is ever less than Num1, you will NEVER again go through this code:
1
2
3
4
5
6
7
while (Input > Num1)
	{
		Tries++;
		cout << "Try a smaller number." << endl;
		cout << "Please enter a number: ";
		cin >> Input;
	}


So the very first time the user guesses a number smaller than the correct answer, your code will NEVER be able to handle them guessing a bigger number than the correct answer.

Put another way, once execution gets to line 24, how could it ever go back to line 17?
Last edited on
Topic archived. No new replies allowed.