[問題] 近似值問題

作者: dblkc (zero)   2022-09-23 18:59:56
開發平台(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
作者: gusion   2022-09-23 19:38:00
因為你的temp是int,float轉int就被無條件捨去,以這個例子來說,第一個temp的運算會是(12345 mod 100) ÷ 10 × 2 = 4.5 × 2 = 9如果你先把4.5存到int,它就變4,再乘以2就是8
作者: breeze08 (linuxer)   2022-09-23 19:40:00
因為fmod跟pow的回傳型態為double,兩者相除得4.5存到型態為long的temp,小數點就被捨棄了
作者: dblkc (zero)   2022-09-23 19:49:00
了解 謝謝各位
作者: steve1012 (steve)   2022-09-28 10:31:00
變數宣告養好習慣要靠近使用的地方 temp 直接在for loop 裏面宣告不會不小心改到啥的

Links booklink

Contact Us: admin [ a t ] ucptt.com