编写一个简易计算器,能实现最基本的加减乘除四则运算。
#include <iostream>
using namespace std;
int main()
{
double num1,num2;
char op; // 运算符号
char flag; // 是否继续运算,'Y'或'y'表示是,'N'或'n'表示否
while(true)
{
cout << "Enter first number:" << endl;
cin >> num1;
cout << "Enter second number:" << endl;
cin >> num2;
while(true)
{
cout <<"Please input operator(+,-,*,/):" << endl;
cin >> op;
if('+' == op)
{
cout << num1 << " + " << num2 << " = " << num1 + num2 << endl;
break;
}
else if('-' == op)
{
cout << num1 << " - " << num2 << " = " << num1 - num2 << endl;
break;
}
else if('*' == op)
{
cout << num1 << " * " << num2 << " = " << num1 * num2 << endl;
break;
}
else if('/' == op)
{
if(0 == num2)
{
cout << "Number can't be divided by 0" << endl;
break;
}
cout << num1 << " / " << num2 << " = " << num1 / num2 <<endl;
break;
}
else
{
cout << "Invalid input" << endl;
continue;
}
}
cout << "Do you want to continue the program?(Y/N)" << endl;
cin >> flag;
if('N' == flag || 'n' == flag)
{
break;
}
else if('Y' == flag || 'y' == flag)
{
continue;
}
}
return 0;
}
运行结果:
3
Enter second number:
5
Please input operator(+,-,*,/):
+
3 + 5 = 8
Do you want to continue the program?(Y/N)
y
Enter first number:
4
Enter second number:
5
Please input operator(+,-,*,/):
/
4 / 5 = 0.8
Do you want to continue the program?(Y/N)
y
Enter first number:
1
Enter second number:
0
Please input operator(+,-,*,/):
/
Number can't be divided by 0
Do you want to continue the program?(Y/N)
n
--------------------------------
Process exited after 30.04 seconds with return value 0
请按任意键继续. . .
本文分享自 KidsCode少儿编程 微信公众号,前往查看
如有侵权,请联系 cloudcommunity@tencent.com 删除。
本文参与 腾讯云自媒体同步曝光计划 ,欢迎热爱写作的你一起参与!