2

This program is based on the program in K&R in the input/output section

#include <stdio.h>


 main(){

double sum, v;

sum = 0;

while (scanf("%1f",&v)==1)
    printf("\t%.2f\n",sum+=v);
return 0;
}

It compiles ok. But when trying to run, from any input the output is "-NAN", presumably NOT A NUMBER. I have no idea why. Any advice would be appreciated.

Brian Tompsett - 汤莱恩
  • 5,753
  • 72
  • 57
  • 129
  • It seems I may have fixed it by changing double to float. Which makes sense, since the input and output are floats. But in K&R they use double. –  Feb 16 '11 at 00:40

3 Answers3

6

The format code is wrong in scanf. It should be %lf (with lower case L), not %1f.

 while (scanf("%lf",&v)==1)

This is because %lf scans for a double, and %f scans for a float. For details, see scanf format codes.

Reed Copsey
  • 554,122
  • 78
  • 1,158
  • 1,373
  • +1 for an excellent catch. While my answer would work, yours is "more correct" – corsiKa Feb 16 '11 at 00:42
  • I'm sure it was just a mis-read, given how close "1" and "l" look in text. – Reed Copsey Feb 16 '11 at 00:44
  • Thanks. That's what happens when you mindlessly copy code. But if I use "lf", it still gives -NAN if sum and v are floats. It only works if they are double. Do you know why? –  Feb 16 '11 at 00:46
  • Because "%lf" is for double values and "%f" for floats. See the documentation for format codes http://www.dgp.toronto.edu/~ajr/209/notes/printf.html – Constantin Feb 16 '11 at 00:51
  • @JJG scanf (and printf) are varargs functions so they don't know the types of their arguments; they must manually pluck them off the stack. Since floats and doubles have different sizes, passing a float when a double is expected or v.v. results in garbage -- which will often be interpreted as NAN. – Jim Balter Feb 16 '11 at 06:44
0

Try changing the double to a float.

corsiKa
  • 81,495
  • 25
  • 153
  • 204
0
scanf("%1f",&v)

You reading a float, but your variable is a double. Try:

scanf("%lf",&v)
Constantin
  • 8,721
  • 13
  • 75
  • 126