Reputation: 67
I am having problem with floating point numbers. I think something is clashing here.
The output is :
My code :
#include <stdio.h>
int main(){
double y;
printf("enter a decimal number: ");
scanf("%f", &y);
printf("%f\n", y);
fflush(stdin);
getchar();
return 0;
}
I am using Dev C++ 4.9.9.2 and first of all, I have to flush the carriage return out several times if it's not read previously . So if there is any alternative there then tell me. And secondly the output is giving this...
Upvotes: 0
Views: 5017
Reputation: 20244
You are using the wrong format specifier in the scanf
and doing this will result in UB(Undefined Behaviour).The correct format specifier for a double
is %lf
while that of a float is %f
. So Just change your scanf
to
scanf("%lf",&y);
Upvotes: 1
Reputation: 53006
Use
scanf("%lf", &y);
instead. Since scanf("%f", &y);
works for float
s only.
If you enable compiler warnings it would tell you that the format specifier "%f"
expects a float *
and not double *
argument.
Upvotes: 3
Reputation: 106012
Using wrong format specifier invoke undefined behavior and that's why you are getting unexpected result. Once UB is invoked, you may either get expected or unexpected result. Nothing can be said.
Use %lf
to read double
type data.
Upvotes: 2