使字符表示运算符c ++

时间:2014-02-04 17:09:25

标签: c++ math char operators

我正在尝试编写一个带两个数字的程序,并允许用户输入a,s,m或d。基本上我要做的是使字符分别表示加法,减法,乘法和除法。问题是,我不确定如何做到这一点。这是我到目前为止的代码。

#include "stdafx.h"
#include <iostream>

using namespace std;

int main()
{
double num1;
double num2;
char operation;

cout<<"Enter the first number: ";
cin>>num1;
cout<<"Enter the second number: ";
cin>>num2;
cout<<"What would you like to do with the numbers? a-addition, s=subtraction, m=multiplacation, d=division";
cin>>operation;

2 个答案:

答案 0 :(得分:2)

您使用开关:

switch (operation) {
  case 'a': // addition
    break;
  case 's': // subtraction
    break;
  // ...
  default: // none of these
    break;
}

答案 1 :(得分:2)

检查switch声明:

#include "stdafx.h"
#include <iostream>

using namespace std;

int main()
{
double num1;
double num2;
char operation;

cout<<"Enter the first number: ";
cin>>num1;
cout<<"Enter the second number: ";
cin>>num2;
cout<<"What would you like to do with the numbers? a-addition, s=subtraction, m=multiplacation, d=division";
cin>>operation;

switch(operation)
{
    case 'a':
        ... // Addition code
        break;
    case 's':
        ... //Substraction code
        break;
    ...

}

你也可以使用if和else,每种类型的操作都有一个。

另外,作为提示,请考虑验证输入数据(尝试在程序中输入更多字符或无效选项)。