使用scanf读取浮点值时出错

问题描述 投票:0回答:2

我在读取此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作为输出。

c floating-point scanf format-specifiers
2个回答
2
投票

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

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 =]


0
投票

%lf用于读取double,而%Lf用于读取long double。因此,在整个代码中,如果将%lf替换为%Lf,它将可以正常工作。

demo

© www.soinside.com 2019 - 2024. All rights reserved.