使用 scanf 读取浮点值时出错
Error while reading floating point values using scanf
我在读取此 C 代码片段的两个浮点值时遇到问题:
#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 作为输出。
了解如何在编译器中启用警告并且不要忽略它们。
a.c:10:11: warning: format ‘%lf’ expects argument of type ‘double *’, but argument 2 has type ‘long double *’ [-Wformat=]
a.c:10:15: warning: format ‘%lf’ expects argument of type ‘double *’, but argument 3 has type ‘long double *’ [-Wformat=]
a.c:11:12: warning: format ‘%lf’ expects argument of type ‘double’, but argument 2 has
type ‘long double’ [-Wformat=]
%lf
用于读取double
,而%Lf
用于读取long double
。因此,如果您将 %lf
替换为 %Lf
,那么通过您的代码,它将正常工作。
我在读取此 C 代码片段的两个浮点值时遇到问题:
#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 作为输出。
了解如何在编译器中启用警告并且不要忽略它们。
a.c:10:11: warning: format ‘%lf’ expects argument of type ‘double *’, but argument 2 has type ‘long double *’ [-Wformat=]
a.c:10:15: warning: format ‘%lf’ expects argument of type ‘double *’, but argument 3 has type ‘long double *’ [-Wformat=]
a.c:11:12: warning: format ‘%lf’ expects argument of type ‘double’, but argument 2 has
type ‘long double’ [-Wformat=]
%lf
用于读取double
,而%Lf
用于读取long double
。因此,如果您将 %lf
替换为 %Lf
,那么通过您的代码,它将正常工作。