Accumulation NAN

Hi, sorry, this is Part 2 of a similar assignment. But there's a couple things I don't understand and Google isn't really helping me and my teacher is the very dictionary term of unreliable. Before I continue, here's the code:

#include <iostream>
using namespace std;

double accumulate2(double acc, double num, char op)
{
cout << "Enter a number: " << endl;
cin >> num;

if (op == '+'){
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 (+, -, *, or /): " << endl;
cin >> op;
while (op == '+' || op == '-' || op == '*' || op == '/')
{
acc = accumulate2(acc, num, op);

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

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


As with my last one, the end result should be:
0
+ 1 = 1
* 5 = 5
- 3 = 2
+ 7 = 9
etc.

The assignment requires me to use "acc = accumulate2(acc, num, op);" (Which I don't understand the logic of.) and "double accumulate2(double acc, double num, char op)" call on top. As the code stands, every entry is nan, which I know means not a number.

So my question to you all is:
How is this nan being formed and how can I correct it.

Also, so I actually understand why I'm being forced to write it this way, can someone explain the significance of the double specifically being a call instead of a void or whatever as well as why my accumulator needs to be equal to my call?
I really appreciate it! I learn a lot more here than in class!
Depending on your compiler and settings, there should be a warning when the program is compiled. I get this:
In function 'double accumulate2(double, double, char)':
[Warning] no return statement in function returning non-void [-Wreturn-type]

That identifies the problem. The function is supposed to return a value. But it doesn't. That means when you later try to do
 
    acc = accumulate2(acc, num, op);
the acc = is looking for some value to assign to the variable but it doesn't find anything there. Hence NAN.

The solution is straightforward. Add the line
 
    return acc;
just before the closing brace of function accumulate2()

For more information on functions which return a value, see the first example, int addition (int a, int b) in the tutorial:
http://www.cplusplus.com/doc/tutorial/functions/
Last edited on
Ahhh, I see now. I'll read up on that link you sent as well! :)

Yeah, my IDE didn't give me an error message and said everything was fine so you can imagine my confusion.

Thank you so much!
Topic archived. No new replies allowed.