Why does this sentinel loop keep returning a wrong value?

  accumulator, c++, while-loop

In this program, the program takes two types inputs; numbers and operators and keeps going until the user enters "="
which is the sentinel and marks the end of the expression after which, the program should return the total value of the expression.

A sample run of the program should look something like this:

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

But the output that I am getting is:

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

It seems that when the user inputs = the program doesn’t seem to know what to do. But I don’t know what changes do I make to the code to make it work.

This is my code:

// 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;
}

Source: Windows Questions C++

LEAVE A COMMENT