I have been working on this program for a few days. It is a simple calculator in a do...while loop. The loop is supposed to run and continuously compute the total of all inputs until the user enters an 'X' as their input. The loop I have runs once and then stops.
The other problem I'm having with this is that I want to output "Cannot divide by 0" if a person tries to and I have not been able to figure this out.
Here is what I have so far:
#include <iostream>
usingnamespace std;
/*Write a calculator which asks the user for an operation and then a number.
Calculate the total of that number and the previous total. Begin the total at "0".
Stop the program when the user enters "X".
*/
int main ()
{
double total=0, response=0;
char operation;
do
{
cout << "Current total is " << total << endl;
cout << "Enter an operation: + - * / (or enter X to exit): ";
cin >> operation;
cin.ignore();
if (operation=='X') break;
cout << "Enter a number: ";
cin >> response;
cin.ignore();
//Calculations are working correctly.
if (operation=='+')
total=total+response;
if (operation=='-')
total=total-response;
if (operation=='*')
total=total*response;
if (operation=='/')
total=total/response;
if ((operation=='/') && (response=='0'))
cout << "Can not divide by zero!" << endl; /*This cout isn't displaying when the operation is division and the response is 0 */
cout << "Current total is " << total << endl;
}
while ((operation!='X') && ((operation=='+') && (operation=='-') &&(operation=='*')
&& (operation=='/'))); /*The program isn't looping.
I want it to keep going until 'X' is entered*/
}
Take a look at your condition in the while(). Check your logical operators - you're using &&'s, and that condition will never be true. That is why the loop breaks.
I just saw that your program already has the check for zero.
The check has to be done before the division is performed, otherwise it'll be too late.
That should be VERY obvious, though.
I understand what you're talking about in theory but I still am not sure where to put the check. I don't care if 0 is entered for anything other than division. I tried moving
1 2
if ((operation=='/') && (response=='0'))
cout << "Can not divide by zero!" << endl;
around but haven't had any success with it. Where would you recommend I put it?