Simple C Program
-
14-11-2019 - |
Question
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.
OTHER TIPS
Try changing the double to a float.
scanf("%1f",&v)
You reading a float, but your variable is a double. Try:
scanf("%lf",&v)
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow