Accumulating number won't accumulate

Hi folks. Before you get the wrong idea, no this has nothing to do with std::accumulate. The assignment I have is about accumulating a number with each entry:
+ 1 = 1
+ 2 = 3
* 2 = 6
/ 3 = 2
and so on...

It's 99% done. I got it to loop how I want and say what I want but I came across an interesting problem as I wrote it that I couldn't find an answer to. Here's the code as I have it so far:


#include <iostream>
using namespace std;

void accumulate(double & acc, double num, char op) // Teacher requires this
{
cout << "Enter a number: " << endl;
cin >> num;

if (op = '+'){
acc + num;
acc = acc + num;
}
if (op = '-'){
acc - num;
}
if (op = '*'){
acc * num;
}
if (op = '/'){
acc / num;
}
}

int main()
{
double acc = 0.0;
double num = 0.0;
char op;

cout << "Accumulated value: " << acc << endl;
cout << "\n";

cout << "Enter the operand (+, -, *, o r/): " << endl;
cin >> op;
while (op == '+' || op == '-' || op == '*' || op == '/')
{
accumulate(acc, op, num);

cout << "\nAccumulated value is now: " << acc << endl;
cout << "\n";

cout << "Enter the operand (+, -, *, o r/): " << endl;
cin >> op;
}
}


When I add, as displayed above, it does it's job. But if I try to put in the rest (acc = acc- num, acc = acc * num, and acc = acc / num), the accumulated number stays at 0, no matter what operand I use. The same is true if I use the other operands by themselves: They will do the math as they should, but will stay 0 if the others are added. I don't see the logic behind it. Adding the last three shouldn't affect it since they are separate if statements, but they do. Why is that? Can someone show me how to fix this?
Thank you!
1
2
3
4
5
6
7
8
9
10
11
12
13
if (op = '+'){
acc + num;
acc = acc + num;
}
if (op = '-'){
acc - num;
}
if (op = '*'){
acc * num;
}
if (op = '/'){
acc / num;
}

You should be using == for comparing values not =.
You should also be doing acc -= num etc.
Last edited on
No good, it still does the same thing: 0's all around.
You need to pass the function arguments in the correct order.

void accumulate(double & acc, double num, char op)

accumulate(acc, op, num); <-- Not correct
I sincerely did not know that. Nor the +=, -= you mentioned. All that got it working as intended

This helps so much! You're a lifesaver, Hipp! :D
I sincerely did not know that.

How did you think the compiler would know which value was supposed to be which, if you didn't put them in the right order?
Topic archived. No new replies allowed.