【发布时间】:2014-03-16 12:55:28
【问题描述】:
我用 C++ 编写了一个非常简单的计算器程序,它运行良好!但是有人能解释一下我如何修改这段代码,使它能够一次添加两个以上的数字吗?
因此,例如,我希望用户能够执行 2 + 2 + 2,而不是执行 2 + 2。但每次我尝试时,它只会添加前两个“2”并给出 4,无论如何many + 2 你在它后面输入。
代码如下:
#include <iostream>
using namespace std;
// input function
void Input (float &x, float &y);
float a=1.0, b=1.0, result;
char operation;
int main ()
{
cout << "A simple calculator \n\n";
cin >> a >> operation >> b;
Input (a,b);
cout << result << endl;
system ("pause");
return 0;
}
void Input (float &x, float &y)
{
a = x;
b = y;
switch (operation)
{
case '+':
result = x + y;
break;
case '-':
result = x - y;
break;
case '*':
result = x * y;
break;
case '/':
result = x / y;
break;
default:
cout << "Improper operation. Please input a correct calculation operation: \n";
cin >> a >> operation >> b;
Input (a, b);
}
}
谢谢大家!
【问题讨论】:
-
您没有读取超过 2 个数字和单个运算符的循环 - 为什么
operation是全局而不是评估函数Input的参数? -
为什么你希望这段代码执行两次计算?您检索两个操作数和一个操作(cin >> a >> operation >> b)。向我们展示您尝试执行两次计算的代码。
标签: c++ calculator