Switch语句中的C ++ Maths

时间:2017-08-09 05:55:51

标签: c++ math

所以我希望做一个简单的数学方程式打印菜单,然后将操作符作为char。然后,它会提示用户输入两个数字然后打印生成的问题,然后以如下格式回答:10 + 20 = 30

#include <iostream>
#include <cstdio>

using namespace std;

int main()
{
    //Variables
    char op_choice;
    int usrnum_1;
    int usrnum_2;

    //Menu
    cout << "Operator Menu\n\n";
    cout << "+\n";
    cout << "-\n";
    cout << "*\n";
    cout << "/\n";
    cout << "%\n\n";

    cout << "Choice:";
    cin >> op_choice;
    cout << "\nNumbers:";
    cout << "\n\nEnter TWO numbers to complete an arithmitic operation with the " << op_choice << " operator: \n";
    cout << "eg: 1 + 2 = 3\n";
    cout << "\nNumber 1: ";
    cin >> usrnum_1;
    cout << "Number 2: ";
    cin >> usrnum_2;

    switch (op_choice)
    {
        case '+':
            break;
        case '-':
            cout << "\nYou picked " << usrnum_1 << " - " << usrnum_2 << " = ";
            cout << usrnum_1 - usrnum_2;
            break;
        case '*':
            cout << "\nYou picked " << usrnum_1 << " X " << usrnum_2 << " = ";
            cout << usrnum_1 * usrnum_2;
            break;
        case '/':
            cout << "\nYou picked " << usrnum_1 << " / " << usrnum_2 << " = ";
            cout << usrnum_1 / usrnum_2;
            break;
        case '%':
            cout << "\nYou picked " << usrnum_1 << " % " << usrnum_2 << " = ";
            cout << usrnum_1 % usrnum_2;
            break;
        default:
            cout << "\nYou made an illegal choice.\n";
    }

    cout << "\nYou picked " << usrnum_1 << " " <<  op_choice << " " <<  usrnum_2 << " = ";
    cout << usrnum_1 << op_choice << usrnum_2;

    getchar();
    return 0;
}

我实际上已经得到了这段代码,你可以从减法和乘法等中看到。但是我希望在交换机块之外得到cout(我开始做并且正在使用add进行测试)。有没有办法让这项工作没有将op_choice最初变成int?或者将cout语句放入switch块?使用if-else-if语句会更好吗?

1 个答案:

答案 0 :(得分:2)

首先,cout << usrnum_1 << op_choice << usrnum_2; 是此类代码的最佳代码构造。

问题在于你的通用输出概念

cout << usrnum_1 + usrnum_2;

无法接近您想要的计算:

usrnum_1
  1. 我希望当你看到这些线彼此靠近时,第一个问题就清楚了。他们只做不同的事情:

    1. 第一个打印op_choice,然后是usrnum_2,最后是op_choice。没有任何魔法发生,char只是要打印的usrnum_1 + usrnum_2
    2. 第二个执行加法<<(算术运算符比按位移位运算符char op_choice = '+'具有to_numeric),然后输出加法结果。
  2. 第二个更重要的问题是+(在运行时设置)不能轻易地成为C ++代码中的算术运算符a + b,因为它是一种编译语言。 编译器采用表达式+并将其转换为整数加法的机器指令。你的编译程序不知道整数加法的指令与数字43(switch的ASCII代码)有关,直到你明确地告诉它(使用switch,最好是)。

  3. 那么如何让它发挥作用?正如评论者建议的那样,您必须将计算保留在int result; switch (op_choice) { case '+': result = usrnum_1 + usrnum_2; break; case '-': result = usrnum_1 - usrnum_2; break; case '*': result = usrnum_1 * usrnum_2; break; case '/': result = usrnum_1 / usrnum_2; break; case '%': result = usrnum_1 % usrnum_2; break; default: cout << "\nYou made an illegal choice.\n"; return 1; } cout << "\nYou picked " << usrnum_1 << " " << op_choice << " " << usrnum_2 << " = "; cout << result; 块中,并仅将打印部分带出来。

    {{1}}

    higher priority