作者dblkc (zero)
看板C_and_CPP
标题[问题] 近似值问题
时间Fri Sep 23 18:59:56 2022
开发平台(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://webptt.com/cn.aspx?n=bbs/C_and_CPP/M.1663930800.A.8DF.html
1F:推 gusion: 因为你的temp是int,float转int就被无条件舍去,以这个例 09/23 19:38
2F:→ gusion: 子来说,第一个temp的运算会是 09/23 19:38
3F:→ gusion: (12345 mod 100) ÷ 10 × 2 = 4.5 × 2 = 9 09/23 19:38
4F:→ gusion: 如果你先把4.5存到int,它就变4,再乘以2就是8 09/23 19:38
5F:→ breeze08: 因为fmod跟pow的回传型态为double,两者相除得4.5 09/23 19:40
6F:→ breeze08: 存到型态为long的temp,小数点就被舍弃了 09/23 19:41
7F:→ dblkc: 了解 谢谢各位 09/23 19:49
8F:→ steve1012: 变数宣告养好习惯要靠近使用的地方 temp 直接在for lo 09/28 10:31
9F:→ steve1012: op 里面宣告不会不小心改到啥的 09/28 10:31