+ 1

Hey im totally new to this. Can someone please explain why the code given below does not properly work?

#include <iostream> Using namespace std; Int main() { Int a; Int b; Int x = a + b; Int sum = x + x; Cout << "insert a number \n"; Cin >> a; Cout << "Insert another number \n"; Cin >> b; Cout << "the answer is : " << sum << endl; Return 0; }

30th Mar 2019, 11:44 PM
Norbert Ramaj
2 ответов
+ 3
You declare a and b, but you don't give an initial value; so a and b have random values (whatever was there in memory before you declared you want to use that spot). x = a + b now sums up these two random values. What will be the result? Something random. You decide that sum is to be x + x. So what is random + random? Do you begin to see a pattern? Yeah - random! 😉 Now you read user input into a and b. a and b store new values now, the former random values are gone. sum though is still the result of (a+b) + (a+b) equals (x) + (x) equals random + random. Because you made it so earlier. In short: The sum you output has no relation to what the user input. To correct this: First take the user input. Then sum up the user input. Then output the sum.
31st Mar 2019, 12:05 AM
HonFu
HonFu - avatar
0
Int a and b must be initialized first..😂
31st Mar 2019, 2:21 AM
Rudolph John A. Agpoon
Rudolph John A. Agpoon - avatar