【问题标题】:Why does this sentinel loop keep returning a wrong value?为什么这个哨兵循环总是返回错误的值?
【发布时间】: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


    【解决方案1】:

    您需要调试自己的代码。逐行观察每个变量,看看程序的执行与您在每一步的预期有何不同。

    如果你这样做,你会看到你将每个运算符应用于它之前的数字:

    iteration num op total
    1st 1.0 + 0 + 1 = 1
    2nd 3.4 + 1 + 3.4 = 4.4
    3nd 4.8 - 4.4 - 4.8 = -0.4
    4th 2.3 = while condition false, body not entered

    total 最终成为 -0.4


    你可以做什么:

    • 读取次数

    • total = num

    • 循环:

      • 读取操作

        • 如果 op 是 =break
      • 读取次数

      • total = total op num

    【讨论】:

    • 我是编程概念的新手,所以请您详细说明您的答案。
    • 我不相信用勺子喂答案会有帮助,尤其是对于初学者。如果您对我的回答有任何具体问题,我很乐意回答,但我不会提供代码,因为我觉得我为您提供了编写代码所需的信息。
    猜你喜欢
    • 2014-04-01
    • 1970-01-01
    • 1970-01-01
    • 2011-01-11
    • 1970-01-01
    • 1970-01-01
    • 2023-01-02
    • 1970-01-01
    相关资源
    最近更新 更多