C语言:scanf函数使用float和double类型产生不同的结果?

时间:2014-03-02 21:15:02

标签: c floating-point double scanf floating-accuracy

    **Code A returns the correct conversion: 6.55957.**

    #include <stdio.h>
    #include <stdlib.h>
    #include <math.h>

    float convert(float currencyA)
    {
    float currencyB = 0;
    currencyB = 6.55957 * currencyA;
    return currencyB;
    }

    int main(int argc, const char *argv[])
    {

    float amount = 0;

    printf("How much\n");
    scanf("%f", &amount);


    printf("You get %f in currencyB", convert(amount));

    return 0;
    }

**Code B returns an incorrect conversion: 0.051247.**

#include <stdio.h>
#include <stdlib.h>
#include <math.h>

double convert(double currencyA)
{
double currencyB = 0;
currencyB = 6.55957 * currencyA;
return currencyB;
}

int main(int argc, const char *argv[])
{

double amount = 0;

printf("How much\n");
scanf("%f", &amount);


printf("You get %f in currencyB", convert(amount));

return 0;
}

如果我删除 printf scanf ,并将1作为值分配给“amount”变量,则结果是正确的。

我怀疑 scanf 导致错误。如果是这样,为什么会这样?

感谢您阅读并随时询问您需要的任何其他信息。

1 个答案:

答案 0 :(得分:5)

double的正确格式说明符为%lf,而不是%f