[问题] 近似值问题

楼主: 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