I'm wondering what's goin on in this code. It's relatively simple, but it's definitely not giving the right output. sum for some reason ends up being in the millions, even when the two numbers input are like 5 and 5, lol.
#include <iostream>
usingnamespace std;
int main()
{
int a;
int b;
int sum;
cout << "enter a: \n";
cin >> a;
cout << "enter b: \n";
cin >> b;
cout << "a plus b is: " << sum;
sum = a + b;
return 0;
}
#include <iostream>
usingnamespace std;
int main()
{
int a;
int b;
int sum;
cout << "enter a: \n";
cin >> a;
cout << "enter b: \n";
cin >> b;
cout << "a plus b is: " << sum;
sum = a + b;
return 0;
}
You have to have the math done BEFORE you display the variable, otherwise you'll get something you don't want.
1 2 3 4 5 6 7 8
cout << "enter a: \n";
cin >> a;
cout << "enter b: \n";
cin >> b;
sum = a + b;
cout << "a plus b is: " << sum;
Hmm I don't think that was it. Maybe it's the compiler, but I can't see that unless I clicked something I shouldn't have...which is possible, unless the code is still wrong..
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16
int main()
{
int a;
int b;
int sum;
sum = a + b;
cout << "enter a: \n";
cin >> a;
cout << "enter b: \n";
cin >> b;
cout << "a plus b is: " << sum;
return 0;
}
Your first version tried to output 'sum' before you calculated 'sum = a + b'. Now, you're trying to calculate 'sum = a + b' before you know what value a and b have.
Put your calculation after "cin >> b;" and before the output of sum.
nope, it's not the compiler. You calculated sum before asking the user for the values of a and b.
On the last code above you have not initialised any values so sum will contain the result of whatever was in memory for a and b, which could be anything.
Go back to your first code but put cout << "a plus b is: " << sum;
after sum = a + b;
as FalterrisAunvre suggested.
Never mind, I ran the previous code, fixed and it's still giving a bogus answer. I don't know what the deal is. It's like when use input is used things go haywire.
There's nothing wrong with the compiler. Your code should look like this:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17
int main()
{
int a;
int b;
int sum;
cout << "enter a: \n";
cin >> a;
cout << "enter b: \n";
cin >> b;
sum = a + b;
cout << "a plus b is: " << sum;
return 0;
}
Note that no variable is used in any way before it is assigned a value.
Awesome, thanks for the information. I was wondering. How come sum = a + b; has to go just before the output, and can't be placed up by the variable declarations? I mean, it still puts it before the math is done.
Since before you enter a's (cin >> a) and b's (cin >> b) value, they have none. A declaration like this: int a; will leave the variable with no value. So if you do sum = a + b before a and b has any value, sum will get some gibberish value, and may cause a run-time error.