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; }
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;
}
+ 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.
+ 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;
}