当前位置 : 主页 > 编程语言 > java >

小朋友学C++(24):实现简易计算器

来源:互联网 收集:自由互联 发布时间:2022-08-10
一、需求 编写一个简易计算器,能实现最基本的加减乘除四则运算。 二、代码实现 #include iostream using namespace std; int main() { double num1,num2; char op; // 运算符号 char flag; // 是否继续运算,


一、需求

编写一个简易计算器,能实现最基本的加减乘除四则运算。

二、代码实现

#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
请按任意键继续. . .少儿编程QQ群:581357582,少儿英语QQ群:952399366

小朋友学C++(24):实现简易计算器_四则运算


网友评论