This question already has answers here:
Closed 2 years ago.
Why does 5/2 results in '2' even when I use a float? [duplicate]
(3个答案)
#include <stdio.h>
int main() {
double x = 10.4, y;
int m = 2;
y = x / m;

printf("%.1f\n", y);//5.2
printf("%.1f\n", (double)(7 / 2)); //3.0, why not 3.5 ?
printf("%.1f\n", 3.5f);//3.5
// the last line prints 3.5,
// why its not rounding down to 3.0 ,as it did above ?
}

有人能解释一下这里发生了什么吗?

最佳答案

printf("%.1f\n", (double)(7 / 2));行中,操作顺序如下:
7/2 = 3
(double)3 = 3.0
printf("%.1f\n", 3.0);// Your problem becomes evident.
要达到预期的行为,请将(double)(7 / 2)更改为7.0 / 2
(即,printf("%.1f\n", 7.0 / 2);则您的代码将正确打印3.5)。
7/2除以两个ints,从而自动将结果截断为3,就像使用integer division一样然后将整数除法的结果转换为double以生成3.0。如果数学表达式中的一个数是adouble,则可以避免所有这些问题,然后将另一个数隐式转换为adouble,从而在结果中生成adouble

关于c - 了解C双格式器占位符,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/46901227/

10-10 04:26