Shubham
Shubham

Reputation: 1153

Error while reading floating point values using scanf

I'm having problem while reading two floating point values for this c code snippet:

#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;
}

When providing 2 and 4 as input, program is displaying 0.000000 as output.

Upvotes: 0

Views: 287

Answers (2)

Himanshu Singh
Himanshu Singh

Reputation: 2165

%lf is for reading double while %Lf is used for reading long double. So through out your code if you replace %lf with %Lf then it will work fine.

demo

Upvotes: 0

David Schwartz
David Schwartz

Reputation: 182885

Learn how to enable warnings in your compiler and don't ignore them.

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

Upvotes: 2

Related Questions