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

一、需求

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

二、代码实现

#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,微信:307591841
公众号.jpg

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值