小朋友学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
请按任意键继续. . .

想了解少儿编程、少儿英语请加微信307591841或QQ307591841

《小朋友学C++(24):实现简易计算器》 公众号.jpg

    原文作者:海天一树X
    原文地址: https://www.jianshu.com/p/72f282489aca
    本文转自网络文章,转载此文章仅为分享知识,如有侵权,请联系博主进行删除。
点赞