0

why is the code not working? Always the answer is 8.

#include <iostream> using namespace std; int main() { int a, b, c = a + b; cin >> a; cin >> b; cout << c; return 0; }

23rd Jan 2019, 9:02 AM
Дронт
Дронт - avatar
3 Réponses
+ 3
Order matters. You are using a and b before initializing them. "c = a + b" means "sum the current values of a and b and store the result into c", and not "c is always equal to the sum of the variables a and b, recalculated each time their values change". int main() { int a, b, c; cin >> a; cin >> b; c = a + b; cout << c; return 0; }
23rd Jan 2019, 9:14 AM
Zen
Zen - avatar
+ 2
Because the value of c is defined as the sum of a and b in the third line and is never changed afterwards. None of the variables a and b is initialized, so c will just hold some random/trash value, in this case 8. If you want c to contain the actual sum of a and b, you need to redefine c = a + b after cin >> a and cin >> b.
23rd Jan 2019, 9:14 AM
Anna
Anna - avatar
+ 1
//why is the code not working? Always the answer is 8. use this method #include <iostream> using namespace std; int main() { int a, b,c; cin >> a; cin >> b; c = a + b; cout << c; return 0; }
23rd Jan 2019, 9:17 AM
Saad Saleem
Saad Saleem - avatar