Click here to Skip to main content
15,897,704 members
Please Sign up or sign in to vote.
1.00/5 (3 votes)
See more:
Is %f not a format specifier for double? I have seen a couple of times that it is..please Explain........................

What I have tried:

C++
#include<stdio.h>
#include<conio.h>
void main()
{
   double d;
   scanf("%f",&d);
   printf("%f",d);
   getch();

}
Posted
Updated 8-Mar-17 5:27am
v4

1 solution

%f is the format code for a float, not a double. Since a double is twice the size of a float, when you read a float value into the memory for a double, the value you get is not correct.
Try %lf instead.
 
Share this answer
 
Comments
Richard MacCutchan 8-Mar-17 11:26am    
Interesting, I wonder why it is not coerced to a double?
OriginalGriff 8-Mar-17 14:09pm    
Because it's a void pointer when it gets to the function - scanf doesn't know you passed it a pointer to a double, and you specifically asked for a float. Just like you can pass a int pointer to a %s scanf (and blow the stack!)
Richard MacCutchan 8-Mar-17 15:47pm    
Duh, my stupid question.
CPallini 8-Mar-17 16:29pm    
5.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)



CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900