output not adding up to correct number

I am learning function overloading and I am a bit confused on the output I am getting. when I add the numbers up from the program on my calculator I get 32 and when the program runs the output is 30. Is there a reason for the program outputting 30 or is my math just wrong.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
include <iostream>
using namespace std;
int manip(int);
int manip(int, int);
int manip(int, double);
int main()
{
int x = 2, y= 4, z;
double a = 3.1;
z = manip(x) + manip(x, y) + manip(y, a);
cout << z << endl;
return 0;
}
int manip(int val)
{
return val + val * 2;
}
int manip(int val1, int val2)
{
return (val1 + val2) * 2;
}
int manip(int val1, double val2)
{
return val1 * (val2);
}
int manip(int, double);

1
2
3
4
int manip(int val1, double val2)
{
return val1 * (val2);
}


The result of this will be 12.4, meaning the function should return a double, not an integer. If it returns an integer it will be rounded down to 12. That's why you're getting 30.

The way you're doing the calculations right now, it's 30.4 ( assuming you return double), not 32.

return val + val * 2; // First 2*2 will be executed then + 2. So it's 6

return (val1 + val2) * 2; // Because of the parenthesis, it's 2 + 4 first then * 2. So it's 12

return val1 * (val2); // just returns 12.4 if you change to double

6 + 12 + 12.4 = 30.4;
Last edited on
Topic archived. No new replies allowed.