为什么我不能通过此代码获得正确的输出?

Ror*_*ell 1 c output

我正在解决一个困扰我一段时间的问题。还是不明白。更改的类型是有道理的m,但我仍然不明白m在此过程中经历了什么。它的价值如何变化?下面是代码。

我已经在代码块上尝试过了。

#include<stdio.h>
int main()
{
    int m=5;
    m = (float)m / (2.0);//There, shouldn't m be 2.500000?
    printf("%f\n", m);
    printf("%0.2f\n",(float)m/2.0);
    getchar();
    return 0;
}
Run Code Online (Sandbox Code Playgroud)

预期结果:

2.500000
1.25
Run Code Online (Sandbox Code Playgroud)

实际结果:

nan
1.00
Run Code Online (Sandbox Code Playgroud)

Bla*_*aze 5

m是一个int。因此m = (float)m / (2.0);,即使这样做,即使(float)m / (2.0)2.5,它也会被截断以存储为mas 2。所以当你这样做

printf("%f\n", m);
Run Code Online (Sandbox Code Playgroud)

您有未定义的行为,因为它是,int并且您说这是float

以后你这样做

printf("%0.2f\n",(float)m/2.0);
Run Code Online (Sandbox Code Playgroud)

and you get 1.0 because m was 2 and you divide it by 2.0. You can get the expected output by changing the type of m to float instead.