0

I tried to write a simple c program that does something with derivatives, but that's not the point of the question: When I run the program, It asks me to input a bunch of floating point values, but it doesn't matter what I input the scanf function will always assign "junk" values to the variables, here's the code:

double a, b, c, d, x, h;
printf("Please enter the coefficient of X cubed: ");
scanf("%3f", &a);
printf("\nPlease enter the coefficient of X squared: ");
scanf("%3f", &b);
printf("\nPlease enter the coefficient of X: ");
scanf("%3f", &c);
printf("\nPlease enter the free coefficient: ");
scanf("%3f", &d);
printf("\nPlease enter x: ");
scanf("%3f", &x);
printf("\nPlease enter the offset: ");
scanf("%3f", &h);

printf("%.3f %.3f %.3f %.3f %.3f %.3f", a,b,c,d,x,h);

I enter the values for a, b, c, d, x and h, but the printf function shows really weird values - completely different from what I entered.

I googled it in every possible way I thought of, and I can't seem to find the reason it happens.

Can someone try to figure out why it happens?

jweyrich
  • 31,198
  • 5
  • 66
  • 97
Omer Tuchfeld
  • 2,886
  • 1
  • 17
  • 24
  • 3
    Read the documents on format strings for `scanf`. They are different from `printf`. You want "%lf". – Gene Jul 23 '12 at 22:29
  • 1
    Related: [Why does scanf() need “%lf” for doubles, when printf() is okay with just “%f”?](http://stackoverflow.com/questions/210590/why-does-scanf-need-lf-for-doubles-when-printf-is-okay-with-just-f) – jweyrich Jul 23 '12 at 22:30
  • 2
    Was it really necessary to down-vote my question? what's wrong with it? – Omer Tuchfeld Jul 23 '12 at 22:31
  • 1
    I didn't downvote (nor am I about to) but I'm guessing the reason was that you can answer this question by looking at man pages. This doesn't show much research effort. – dbeer Jul 23 '12 at 22:34
  • I did look on many pages on printf and scanf I found, and none of them said anything about that. I didn't even know what exactly to look for: I thought the problem might have been with me not initializing the variables or something similar, never guessed that such a small syntax mistake would make scanf assign junk values to variables. – Omer Tuchfeld Jul 23 '12 at 22:37
  • 1
    My down vote is for reasons already cited, for having no Accept on the helpful answer, and for an important typo in the title that I don't feel like fixing because it seems merely to be carelessness on the part of the one who posted. – Smandoli May 25 '16 at 13:25

2 Answers2

4

Use lf conversion specifier to read double values and not f conversion specifier which is specifief to read float values. fscanf and fprintf functions are not symmetrical in that respect.

ouah
  • 142,963
  • 15
  • 272
  • 331
0

You have to use %lf or %g to extract doubles, not %f.

jweyrich
  • 31,198
  • 5
  • 66
  • 97