看板 C_and_CPP 關於我們 聯絡資訊
開發平台(Platform): (Ex: Win10, Linux, ...) Linux 編譯器(Ex: GCC, clang, VC++...)+目標環境(跟開發平台不同的話需列出) 額外使用到的函數庫(Library Used): (Ex: OpenGL, ...) 問題(Question): 我將line 42 最後的*2 移到line 43的話,第一個temp的直就是我想要的8,為何只是分成兩行寫而已會得到不同答案? 餵入的資料(Input): 12345 預期的正確結果(Expected Output): 想讓第一個temp值為8(因為2 * 4) 錯誤結果(Wrong Output): 第一個temp值為9 程式碼(Code):(請善用置底文網頁, 記得排版,禁止使用圖檔) #include <stdio.h> #include <math.h> int judge(long a, int len); int main(void) { long num; printf("Number: "); scanf("%li", &num); // Claim a new variable "check" to see how length the num is long check = num; int count = 0; while (check) { check = round(check / 10); count++; } printf("Length: %d\n", count); int sum = judge(num, count); printf("sum = %d\n", sum); } int judge(long a, int len) { long even = 0, odd = 0, temp; for (int i = 1; i <= len; i++) { // odd terms if (i % 2 != 0) { odd += fmod(a, pow(10, i)) / pow(10, i - 1); printf("odd: %li\n", odd); } // even terms else { temp = fmod(a, pow(10, i)) / pow(10, i - 1) * 2; // temp *= 2; printf("temp: %li\n", temp); even += temp / 10 + temp % 10; printf("even: %li\n", even); } } return odd + even; } 補充說明(Supplement): https://glot.io/snippets/gdt9xrcs0a -- ※ 發信站: 批踢踢實業坊(ptt.cc), 來自: 180.177.0.123 (臺灣) ※ 文章網址: https://www.ptt.cc/bbs/C_and_CPP/M.1663930800.A.8DF.html
gusion: 因為你的temp是int,float轉int就被無條件捨去,以這個例 09/23 19:38
gusion: 子來說,第一個temp的運算會是 09/23 19:38
gusion: (12345 mod 100) ÷ 10 × 2 = 4.5 × 2 = 9 09/23 19:38
gusion: 如果你先把4.5存到int,它就變4,再乘以2就是8 09/23 19:38
breeze08: 因為fmod跟pow的回傳型態為double,兩者相除得4.5 09/23 19:40
breeze08: 存到型態為long的temp,小數點就被捨棄了 09/23 19:41
dblkc: 了解 謝謝各位 09/23 19:49
steve1012: 變數宣告養好習慣要靠近使用的地方 temp 直接在for lo 09/28 10:31
steve1012: op 裏面宣告不會不小心改到啥的 09/28 10:31