前往小程序,Get更优阅读体验!
立即前往
首页
学习
活动
专区
工具
TVP
发布
社区首页 >专栏 >小朋友学C++(24):实现简易计算器

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

作者头像
海天一树
发布2018-12-24 16:02:09
6920
发布2018-12-24 16:02:09
举报
文章被收录于专栏:海天一树海天一树

一、需求

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

二、代码实现

代码语言:javascript
复制
#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;
}

运行结果:

代码语言:javascript
复制
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
请按任意键继续. . .
本文参与 腾讯云自媒体分享计划,分享自微信公众号。
原始发表:2018-12-05,如有侵权请联系 cloudcommunity@tencent.com 删除

本文分享自 KidsCode少儿编程 微信公众号,前往查看

如有侵权,请联系 cloudcommunity@tencent.com 删除。

本文参与 腾讯云自媒体分享计划  ,欢迎热爱写作的你一起参与!

评论
登录后参与评论
0 条评论
热度
最新
推荐阅读
目录
  • 一、需求
  • 二、代码实现
领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档