Simple C Program

932 views Asked by At

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.

3

There are 3 answers

5
Reed Copsey On BEST ANSWER

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.

0
corsiKa On

Try changing the double to a float.

0
Constantin On
scanf("%1f",&v)

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

scanf("%lf",&v)