【问题标题】:Error while reading floating point values using scanf使用 scanf 读取浮点值时出错
【发布时间】:2019-12-15 09:06:11
【问题描述】:

我在读取此 c 代码 sn-p 的两个浮点值时遇到问题:

#include<stdio.h>
long double add(long double a, long double b)
{ return a+b; }

int main()
{
 long double a, b;
 printf("Input two FP values: ");
 //Here scanf isn't reading the 2nd value.
 scanf("%lf %lf", &a, &b);
 printf("%lf", add(a,b));
 return 0;
}

当提供 2 和 4 作为输入时,程序显示 0.000000 作为输出。

【问题讨论】:

  • 你没有检查scanf的返回值。此外,您没有告诉我们您为程序提供的实际输入。是 "24" 还是 "24" 还是别的什么? (另外,如果您的编译器没有给您警告,请了解如何启用它们或获得更好的编译器。如果您忽略警告,请不要。)
  • scanf("%f %lf %Lf", &amp;floatvar, &amp;doublevar, &amp;longdoublevar) 甚至更好的if (scanf("%f %lf %Lf", &amp;floatvar, &amp;doublevar, &amp;longdoublevar) != 3) /* error */; 和等效:printf("%f %f %Lf", floatvar, doublevar, longdoublevar);printf("%f %lf %Lf", floatvar, doublevar, longdoublevar);
  • 对于long double,您需要为"%Lf" 转换说明符指定'L'转换。
  • 你用的是什么编译器?请注意,mingw.org 编译器在 long double 的许多方面存在错误(mingw-w64 修复了此问题)

标签: c floating-point scanf format-specifiers


【解决方案1】:

了解如何在编译器中启用警告并且不要忽略它们。

a.c:10:11:警告:格式“%lf”需要“double *”类型的参数,但参数 2 的类型为“long double *”[-Wformat=]

a.c:10:15:警告:格式“%lf”需要“double *”类型的参数,但参数 3 的类型为“long double *”[-Wformat=]

a.c:11:12:警告:格式“%lf”需要“double”类型的参数,但参数 2 有
输入‘long double’ [-Wformat=]

【讨论】:

    【解决方案2】:

    %lf 用于读取double,而%Lf 用于读取long double。因此,如果您将%lf 替换为%Lf,那么它会正常工作。

    demo

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2013-10-15
      • 2017-03-05
      • 1970-01-01
      • 2012-01-18
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多