为什么在我的 c 程序中,当我使用 double 时它只输出 0,但是当我使用 float 时它有效?

Why in my c program when I use double it only puts out 0, but when I instead use float it works?

当我使用float时,像这样:

#include <stdio.h>

int main()
{
    float g;
    float f;

    scanf("%f", &f);
    g = f / .5;
    printf("%f", g);
    return 0;
}

然后输入 2 我得到 4.000。当我用 double 代替 float 时,结果总是 0.000。为什么我错过了什么?

#include <stdio.h>

int main()
{
    double g;
    double f;

    scanf("%lf", &f);
    g = f / .5;
    printf("%lf", g);
    return 0;
}

您需要在此处使用专门用于双打 (%lf) 的格式说明符。

有关不同格式说明符的详细信息,请参阅 format string specifications

作为,

你对编译器撒了谎:扫描时,%f 说你提供了指向 float 的指针。但是您提供了指向 double.

的指针

要修复,请使用 %lf 或将输入声明为 float

请注意,printf 格式存在不对称性,它对 floatdouble 参数都使用 %f。这是有效的,因为 printf 参数被提升为 double (并且不是指针)。