Senasel

What I'm I doing wrong? This simple program I wrote doesn't give me the sum after I input two numbers to add. Any help?

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

using namespace std;

void calculation(int number1, int number2, double add)
{
    add = number1 + number2;
}

int main ()
{
    int num1, num2, sum;
    sum = num1 + num2;
    cout << "Enter a number: ";
    cin >> num1;
    cout << "Enter another number:";
    cin >> num2;
    cout << sum;

    calculation(num1, num2, sum);
    return 0;
}.
num1 and num2 haven't been initialized when you make this statement.

sum = num1 + num2;

If you want the function to do the calculation, then the function can return the calculated sum to your sum variable in main.

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
int calculation(int number1, int number2)
{
    return number1 + number2;
}

int main ()
{
    int num1, num2, sum;
    cout << "Enter a number: ";
    cin >> num1;
    cout << "Enter another number:";
    cin >> num2;
    sum=calculation(num1, num2);
    cout << "The total is " << sum;
    return 0;
}
Last edited on
Don't complicate the code by doing the variable sum to add up the variables together.

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

using namespace std;

void calculation(int number1, int number2)
{
    cout << number1 + number2;
}

int main()
{
int num1, num2;
cout << "Enter a number: ";
cin >> num1;
cout << "Enter another number: ";
cin >> num2;
calculation(num1, num2);  
}


The only reason the sum didn't show up is because in the function calculation, you didn't have a cout. Remember that.
Last edited on
Thanks guys. I ended up know what was wrong with my code and I fixed it. Thanks so much for your help.
Topic archived. No new replies allowed.