【发布时间】:2021-05-11 06:41:59
【问题描述】:
C 语言中的浮点数很奇怪。我知道它通常用作 (float)a/b。但是,我很好奇下面的代码现象的主要原因和原因是什么。
#include <stdio.h>
int main(void)
{
int a=30, b=16;
double divresult;
divresult = a/b;
printf("result1 : %f \n", a/b);
printf("result1 : %f \n", a/b);
printf("result1 : %f \n", a/b);
printf("result1 : %f \n", a/b);
printf("result1 : %f \n", a/b);
printf("result1 : %f \n", a/b);
printf("result1 : %f \n", a/b);
printf("result1 : %f \n", a/b);
printf("result1 : %f \n", a/b);
printf("divresult : %f \n",divresult);
printf("result2 : %f \n", a/b);
printf("result2 : %f \n", a/b);
printf("result2 : %f \n", a/b);
printf("result2 : %f \n", a/b);
printf("result2 : %f \n", a/b);
printf("result2 : %f \n", a/b);
printf("result2 : %f \n", a/b);
printf("result2 : %f \n", a/b);
printf("result2 : %f \n", a/b);
printf("result2 : %f \n", a/b);
printf("result2 : %f \n", a/b);
printf("result2 : %f \n", a/b);
printf("result2 : %f \n", a/b);
return 0;
}
在这里输出
result1 : 0.000000
result1 : 0.000000
result1 : 0.000000
result1 : 0.000000
result1 : 0.000000
result1 : 0.000000
result1 : 0.000000
result1 : 0.000000
result1 : 0.000000
divresult : 1.000000
result2 : 1.000000
result2 : 1.000000
result2 : 1.000000
result2 : 1.000000
result2 : 1.000000
result2 : 1.000000
result2 : 1.000000
result2 : 1.000000
result2 : 1.000000
result2 : 1.000000
result2 : 1.000000
result2 : 1.000000
result2 : 1.000000
为什么会这样?我真的无法理解。一般来说,我们知道计算机不能准确地表示浮点数。但在这种情况下,似乎有一些模式。 “divresult printf”前后值的变化是如何出现的?
【问题讨论】:
-
你为什么要标记 c++?
-
a/b产生一个整数,但您尝试使用%f打印它 -
从编译器读取警告
-
%f 是浮点数的格式说明符,整数除法得到整数。
-
@πάνταῥεῖ 这是错误的副本。问题的情况完全不同
标签: c printf computer-science