Working on a calculator mimicker.

My problem is that I can't get the loop to exit so that I can exit out of the program without actually have to press the "x" button.

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
38
39
40
41
42
43
44
45
46
47
48
49
#include <iostream>
using namespace std;

int main()
{
	float x,y;
	char math,exit;

do
	{
	
cout<<"Please enter number"<<endl;
cin>>x;
cout<<"Enter mathamatical operator"<<endl;
cin>>math;
cout<<"Enter another number"<<endl;
cin>>y;

		

switch(math)
{
case '+':
	cout<<x<<" "<<math<<" "<<y<<" = "<<x+y<<endl;
break;

case '-':
	cout<<x<<" "<<math<<" "<<y<<" = "<<x-y<<endl;
break;

case '*':
	cout<<x<<" "<<math<<" "<<y<<" = "<<x*y<<endl;
break;

case '/':
	cout<<x<<" "<<math<<" "<<y<<" = "<<x/y<<endl;
	if (y==0){
		cout<<"Undefined"<<endl;}
break;
}
cout<<"type y to quit"<<endl;
cin>>exit;
cout<<endl;
}while(exit=='Y' || 'y');

system("pause");

return 0;
}
closed account (jwkNwA7f)
On line 44, it says to keep looping only while exit is equal to y. It should be:
} while (exit != 'Y' || exit != 'y')
I originally had it like that, it just continued looping. Tried it again just to make sure and I can verify that it just keeps looping.
Last edited on
It should be:

while (exit != 'Y' && exit != 'y' )

Note that the original code:

while ( exit == 'Y' || 'y' ) will always evaluate to true because it is equivalent to:
while ( (exit == 'Y') || 'y' ) and since 'y' is non-zero, 'y' evaluates to true.

In the line provided by retsgorf297, while ( exit != 'Y' || exit != 'y' ),
we can take a look at the expression when exit is 'Y' to see why it doesn't work:

while ( 'Y' != 'Y' || 'Y' != 'y' )

which is equivalent to:

while ( false || true )

which simplifies to:

while (true)
Last edited on
Thank you very much cire, it worked but i'm a little confused.

I originally had while ( exit != 'Y' || exit != 'y' )
why won't making the statement true exit the loop?

From what i was understanding i thought the statement would read while exit is not Y or y continue (false), but if it is Y or y (true) exit.
Last edited on
why won't making the statement true exit the loop?


Loops stop iterating when the loop condition is false.
Oh thank you very much.
Topic archived. No new replies allowed.