【发布时间】:2018-04-21 04:36:01
【问题描述】:
当我输入 "printf("%f\n", 5 / 2);" 行时在第 18 行和第 21 行中,我没有得到 2.5000 ......但是 0.0000 和 65,我不明白为什么。
int main(void){int a = 65;
char c = (char)a;
int m = 3.0/2;
printf("%f\n", 5 / 2);
printf("%c\n", c); // output: A
printf("%f\n", (float)a); // output: 65.000000
printf("%f\n", 5 / 2);
printf("%f\n", 5.0 / 2); // output: 2.5000000
printf("%f\n", 5 / 2.0); // output: 2.5000000
printf("%f\n", (float)5 / 2); // output: 2.5000000
printf("%f\n", 5 / (float)2); // output: 2.5000000
printf("%f\n", (float)(5 / 2)); // output: 2.0000000 - we cast only after division and result was 2
printf("%f\n", 5.0 / 2); // output: 2.5000000
printf("%d\n", m); // output: 1
system("PAUSE");
return 0; }
输出是:
0.000000
A
65.000000
65.000000
2.500000
2.500000
2.500000
2.500000
2.000000
2.500000
1
【问题讨论】:
-
第 18 行是哪一个?
-
%f请求double。5 / 2的结果是int(2)。如果您提供与请求类型不同类型的参数,则结果未定义。 -
也许有匹配的副本,但应该是核心问题(使用错误的 printf 格式说明符)。
-
@purplepsycho 不,这不是一个合适的副本——这里的核心问题不是整数除法,而是使用了错误的 printf 格式说明符。