zoukankan      html  css  js  c++  java
  • 7-12 两个数的简单计算器 (10分)

    我使用了C++的map,用key来存储运算符号,value存储一个特定数字,然后用switch来表示运算结果。

    #define _CRT_SECURE_NO_WARNINGS
    #include <iostream>
    #include <string>
    #include <map>
    using namespace std;
    
    int main(void) {
        int a, b;
        float result;
        string c;
        map<string, int> mymap;
        mymap.insert(make_pair("+", 1));
        mymap.insert(make_pair("-", 2));
        mymap.insert(make_pair("*", 3));
        mymap.insert(make_pair("/", 4));
        mymap.insert(make_pair("%", 5));
        cin >> a >> c >> b;
        map<string, int>::iterator iter;
        iter = mymap.find(c);
        if (iter != mymap.end()) {
            switch (iter->second)
            {
            case 1:
                result = a + b;
                break;
            case 2:
                result = a - b;
                break;
            case 3:
                result = a * b;
                break;
            case 4:
                result = a / b;
                break;
            case 5:
                result = a % b;
                break;
            default:
                break;
            }
            cout << result;
        }
        else {
            cout << "ERROR";
        }
        return 0;
    }

    网上的C语言方法也挺不错,记下来

    #include <stdio.h>
    #include <math.h>
    
    int main() {
        int n1, n2;
        char a;
        scanf("%d %c %d", &n1, &a, &n2);
        if (a == '-') {
            printf("%d", n1 - n2);
        } else if(a == '+') {
            printf("%d", n1 + n2);
        } else if(a == '*') {
            printf("%d", n1 * n2);
        } else if (a == '/') {
            printf("%d", n1 / n2);
        } else if(a == '%') {
            printf("%d", n1 % n2);
        } else {
            printf("ERROR");
        }
        return 0;
    }
  • 相关阅读:
    jQuery 事件注册
    jQuery 获取元素当前位置offset()与position()
    jquery scrollTop()与scrollLeft()
    linux常用命令
    php5.6+apache2.4环境配置
    php 开启socket配置
    Node.js的学习路线
    apache配置rewrite及.htaccess文件(转载)
    php 获取域名等Url
    html5的本地存储
  • 原文地址:https://www.cnblogs.com/letwant/p/14303428.html
Copyright © 2011-2022 走看看