【问题标题】:Make a charcter mean an operator c++使字符表示运算符c ++
【发布时间】:2014-02-04 17:09:25
【问题描述】:

我正在尝试编写一个接受两个数字并允许用户输入 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;

【问题讨论】:

  • 简单的switch statement 应该可以。
  • 使用ifswitch 根据operation 的值决定如何处理数字。
  • 第一年 C++ 编程课程问题...
  • 注意:“a”不等于“A”,因为它们是两个不同的字母,需要进行两次不同的比较。

标签: c++ math char operators


【解决方案1】:

查看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,每种类型的操作各使用一个。

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

【讨论】:

    【解决方案2】:

    你使用开关:

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

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2014-02-27
      • 2016-04-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多