#include <iostream.h>
#include <iomanip.h>
int main()
{
double ans, num1, num2;
int choice = 1;
while(choice)
{
cout<<"\n\n1) Add\n2) Subtract\n3) Multiply\n4) Divide\n5) Quit\n\n";
cout<<"What operation would you like to do?: ";
for(cin>>choice;choice<1 || choice>5;cin>>choice)
{
cout<<"\n\n1) Add\n2) Subtract\n3) Multiply\n4) Divide\n5) Quit\n\n";
cout<<"What operation would you like to do?: ";
}
if (choice>0 && choice<5)
{
cout<<"\n\nEnter the first number: ";
cin>>num1;
cout<<"\n\nEnter the second number: ";
cin>>num2;
cout<<"\n------------------------------------\n";
}
if (choice==1)
{
ans=num1+num2;
cout<<"\nThe sum of "<<num1<<" and "<<num2<<" is "<<ans<<endl;
}
elseif (choice==2)//subtraction
{
ans=num1-num2;
cout<<"\nThe difference of "<<num1<<" and "<<num2<<" is "<< ans<<endl;
}
elseif (choice==3)//multiplication
{
ans=num1*num2;
cout<<"\nThe product of " <<num1<< " and " << num2 << " is " << ans << endl;
}
elseif (choice==4) //division
{
if (num2==0)
{
cout<<"\nThe quotient of "<<num1<<" and "<<num2<< " is undefined."<<endl;
}
else
{
ans=num1/num2;
cout<<"\nThe quotient of " <<num1<<" and "<<num2<<" is "<<ans<<endl;
}
}
elseif (choice==5)
{
choice=0; //quiting the while loop
break;
}
cout<<"\n------------------------------------\n";
}
cout<<"\n**************************************";
cout<<"\n\nThank you for using the calculator.";
return 0;
}
This is what I've attempted so far, but not having any luck:
#include <iostream.h>
#include <iomanip.h>
int main()
{
double ans, num1, num2;
int choice = 1;
while(choice)
{
cout<<"\n\n1) Add\n2) Subtract\n3) Multiply\n4) Divide\n5) Quit\n\n";
cout<<"What operation would you like to do?: ";
for(cin>>choice;choice<1 || choice>5;cin>>choice)
{
cout<<"\n\n1) Add\n2) Subtract\n3) Multiply\n4) Divide\n5) Quit\n\n";
cout<<"What operation would you like to do?: ";
}
if (choice>0 && choice<5)
{
cout<<"\n\nEnter the first number: ";
cin>>num1;
cout<<"\n\nEnter the second number: ";
cin>>num2;
cout<<"\n------------------------------------\n";
}
switch (choice){
case'1':
ans=num1+num2;
cout<<"\nThe sum of "<<num1<<" and "<<num2<<" is "<<ans<<endl;
break;
case'2': //subtraction
ans=num1-num2;
cout<<"\nThe difference of "<<num1<<" and "<<num2<<" is "<< ans<<endl;
break;
case'3': //multiplication
ans=num1*num2;
cout<<"\nThe product of " <<num1<< " and " << num2 << " is " << ans << endl;
break;
case'4': //division
if (num2==0)
{
cout<<"\nThe quotient of "<<num1<<" and "<<num2<< " is undefined."<<endl;
}
else
{
ans=num1/num2;
cout<<"\nThe quotient of " <<num1<<" and "<<num2<<" is "<<ans<<endl;
}
break;
case'5':
choice=0; //quiting the while loop
break;
}
cout<<"\n------------------------------------\n";
cout<<"\n**************************************";
cout<<"\n\nThank you for using the calculator.";
return 0;
}
}
One problem is that your variable choice is an integer which is correct. Your case statements are looking for a character. Just take off the single quotes and you'll have better luck.