Simple C Program

故事扮演 提交于 2019-12-11 03:57:16

问题


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.


回答1:


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.




回答2:


Try changing the double to a float.




回答3:


scanf("%1f",&v)

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

scanf("%lf",&v)


来源:https://stackoverflow.com/questions/5011230/simple-c-program

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!