Search code examples
clexical-analysiskernighan-and-ritchie

Simple C Program


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.


Solution

  • 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.