-1
 #include<stdio.h> 
 int main(void)
 {
      double c;
      scanf("%f", &c);
      printf("%f", c);
 }

This is an exerpt from a program I'm attempting to write, but I get the same issue with something this simple. when I run this, and enter "1.0", it prints out "0.007812". I've looked at several previous questions that were similar to mine and could not find an appropriate answer.

rawrdid
  • 3
  • 1

3 Answers3

3

You need to use "%lf" for double.

This is the warning from clang compiler.

warning: format specifies type 'float *' but the argument has type 'double *' [-Wformat] scanf("%f", &c);

Here is the scanf reference. It's format is %[*][width][length]specifier. The specifier for 'floating point number' is f. So we use %f to read float x. To read double x, we need to specify the length as l. Combined the format is %lf.

Peng Zhang
  • 3,475
  • 4
  • 33
  • 41
  • 2
    You are hitting on the most important point. **enable warnings** in your compile string (e.g. `-Wall -Wextra`) and do not accept code until it compiles *without* warnings. Good job. – David C. Rankin Apr 01 '17 at 03:11
1

the outputTry %lf instead of %f

#include<stdio.h>

int main()
{
double c;
scanf("%lf",&c);
printf("%lf",c);
return 0;
}

What you've used is %f, which is used for a regular float datatype. since you've specified double , you need to use %lf , which is long float. it reads a double. hope this helps you.

0

"%f" is the (or at least one) correct format for a double. There is no format for a float, because if you attempt to pass a float to printf, it'll be promoted to double before printf receives it1. "%lf" is also acceptable under the current standard -- the l is specified as having no effect if followed by the f conversion specifier (among others).

Note that this is one place that printf format strings differ substantially from scanf (and fscanf, etc.) format strings. For output, you're passing a value, which will be promoted from float to double when passed as a variadic parameter. For input you're passing a pointer, which is not promoted, so you have to tell scanf whether you want to read a float or a double, so for scanf, %f means you want to read a float and %lf means you want to read a double (and, for what it's worth, for a long double, you use %Lf for either printf or scanf).