【问题标题】:C language: scanf function producing different results with float and double types?C 语言:scanf 函数使用 float 和 double 类型产生不同的结果?
【发布时间】:2014-04-03 17:19:54
【问题描述】:
    **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 作为值分配给“数量”变量,则结果是正确的。

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

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

【问题讨论】:

  • 建议您确保启用编译器警告。许多编译器很容易警告double amount = 0; scanf("%f", &amp;amount);

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


【解决方案1】:

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

【讨论】:

  • 啊哈!对,现在可以正常使用了。我必须修改基础知识。谢谢你的超快回答:)
猜你喜欢
  • 1970-01-01
  • 2023-02-23
  • 2021-05-15
  • 1970-01-01
  • 1970-01-01
  • 2023-03-16
  • 2021-05-10
  • 1970-01-01
  • 2015-08-09
相关资源
最近更新 更多