【发布时间】:2021-11-09 08:13:36
【问题描述】:
在这个程序中,程序接受两种类型的输入;数字和运算符,并一直持续到用户输入“=” 这是哨兵,标志着表达式的结束,之后程序应该返回表达式的总值。
程序的示例运行应该如下所示:
Enter a number followed by an operator and '=' to get the result:
1.0
+
3.4
+
4.8
-
2.3
=
The total value of the expression is 6.9
但我得到的输出是:
Enter a number followed by an operator and '=' to get the result:
1.0
+
3.4
+
4.8
-
2.3
=
The total value of the expression is -0.4
似乎当用户输入= 时,程序似乎不知道该做什么。但我不知道我要对代码进行哪些更改才能使其正常工作。
这是我的代码:
// this program finds the value of the expression-
// defined by the sequence of operands and operators
// the user enters a series of numbers and + or - then,
// " = " when finished
#include <cstdlib>
#include <iostream>
using namespace std;
int main()
{
float total = 0;
float num;
char op;
cout << "Enter a number follwed by an operator and '=' to get the result:\n ";
cin >> num;
cin >> op;
while (op != '=')
{
if (op == '+')
{
total = total + num;
}
if (op == '-')
{
total = total - num;
}
cin >> num;
cin >> op;
}
cout << "\nThe total value of the expression is "<< total << endl;
return 0;
}
【问题讨论】:
标签: c++ while-loop accumulator