Function failure

Once again, working off the basic tutorials. Once again, having trouble taking the extra steps I knew how to take at one point.

This is from Functions (I), the basic addition program. My idea was to allow user input and make an extremely rudimentary calculator. Every combination of numbers yields a result of 66.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <cstdlib>
#include <iostream>

using namespace std;

int addition (int a, int b)
{
    int r;
    r=a+b;
    return (r);
}

int main ()
{
    int x, y, z;
    z = addition (x, y);
    cout << "Please enter two numbers.\n";
    cin >> x >> y;
    cout << "\nThe result is " << z << endl;
    system("PAUSE");
    return 0;
}


I'm pretty sure it has something to do with the way I'm retrieving the values to be added: either line 16 or 18 is my guess. I tried a getline but that didn't even compile and I think stringstream would be incorrect in this case but, I've been wrong before!

Thanks all,

Cob
closed account (4Gb4jE8b)
I have no idea why it would be returning 66 but this should work

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
#include <cstdlib>
#include <iostream>

using namespace std;

int addition (int a, int b)
{
    return a+b; //conciseness
}

int main ()
{
    int x, y;
    cout << "Please enter first number.\n";
    //cin >> x >> y;  error might have something to do with this?
    cin >> x;
    cout << "Please enter second number.\n";
    cin >> y;
    cout << "\nThe result is " << addition(x,y) << endl;
    system("PAUSE");
    return 0;
}
Thank you! This did indeed fix the problem! I wonder if 66 was just a default value for failure lol.
I don't think 66 was a default value, I tried it and the number that continuously popped up was 1981914492.

Well getline is mainly used for string maybe that's why it didn't compile.
z = addition (x, y);

That line was the culprit, although I don't fully understand why it caused the error but when I removed that line and simplified it like headlessgargoyle it worked without changing
cin >> x >> y;

Wait I figured out why the error was putting z = addition (x, y); before inputting x and y. In this case even if you did enter x and y, z will not have that value because when you assigned z the value of addition(x,y) x and y was not inputted yet that's why a default value kept popping. Try your original code and move z=addition (x,y) after entering x and y it should work
Last edited on
Topic archived. No new replies allowed.