C语言 : scanf function producing different results with float and double types?

标签 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;
}

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

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

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

最佳答案

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

关于C语言 : scanf function producing different results with float and double types?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22133566/

相关文章:

c# - 查找大于 double 值的最小 float

java - 在 JSP 上获得双倍值

.net - .NET 中小数、浮点和 double 之间的区别?

c# - 如何保存不断变化的变量的当前值?

c - scanf 的异常行为

c - 在 OpenSSL lib 包含文件中找不到 i2c_ASN1_INTEGER 函数

c++ - NMEA 库 - nmeaINFO 为空

c - 单个主机的阻塞与非阻塞 UDP 套接字

algorithm - 计算两个值的平均值,最小化错误

c - 当除以一个小的负数时,我只得到 0