当我编译代码时
#include <stdio.h>
int main() {
int n, i, j;
float broj;
scanf("%d", &n);
for (i=0; i<=n; ++i) {
j=i;
broj = 0.1 * j;
while (j>=0) {
printf ("%3.1f ", broj-(j*0.1));
j--;
}
printf(" %d. red\n", i);
}
return 0;
}
在第 5 行之后,每隔第 2 行开始将第一个数字打印为 -0.0 而不是 0.0,所以与第 5、7、9 等中的情况类似...
最佳答案
听起来像是一些基本的浮点精度问题。请注意,0.1 不能完全表示为 float ,因此每次使用它时,您都将使用它的近似值。
这意味着像您的代码一样使用 0.1 进行重复计算也会重复近似误差,这可能会导致最终结果与您手动进行相同计算时的预期略有不同。
一如既往,一个很好的引用是 What Every Computer Scientist Should Know About Floating-Point Arithmetic .
关于C - 打印怪异,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/20399193/