[問題] a question about ==

看板EE_DSnP作者 (kanata)時間18年前 (2007/10/16 18:47), 編輯推噓4(405)
留言9則, 2人參與, 最新討論串1/1
in a simple programm for addition as follows: #include <iostream> using namespace std; int main() { int x, y, sum; cout << "Input the first integer: "; cin >> x; cout << "Input the second integer: "; cin >> y; sum == x + y; cout << "The sum is: " << sum << endl; system ("pause"); return 0; } what I've midified is swaping the "=" for "==" I know their difference-- just want to see what will happen, and whichever two numbers i give to it, the "sum" is always a specific number: 2294360 any explanation, please? -- ※ 發信站: 批踢踢實業坊(ptt.cc) ◆ From: 59.117.201.149

10/16 18:57, , 1F
Basically this line "sum == x+y" just do the comparison
10/16 18:57, 1F

10/16 18:58, , 2F
without affecting the value of sum.
10/16 18:58, 2F

10/16 18:58, , 3F
the value of sum is basically the uninitialized value
10/16 18:58, 3F

10/16 18:58, , 4F
in the line "int x, y, sum".
10/16 18:58, 4F

10/16 18:59, , 5F
You can try to initialize sum by, say "int sum = 38"
10/16 18:59, 5F

10/16 19:00, , 6F
and you should see sum is = 38.
10/16 19:00, 6F

10/16 19:00, , 7F
Actually please turn on "-Wall" and you will see the
10/16 19:00, 7F

10/16 19:00, , 8F
warning message "sum is used without initialization"
10/16 19:00, 8F

10/21 00:02, , 9F
那如果要計算sum 要怎麼做?
10/21 00:02, 9F
文章代碼(AID): #1759QzZS (EE_DSnP)