scanf - limit decimal places while reading

戏子无情 提交于 2019-12-10 12:12:01

问题


I know how to limit the decimal and integer while printing values in printf (%x.x ), In my scenario I want to implement that while reading from the console itslef.

So is there any way to llimit the number of decimals in a floating point value while reading using scanf function?

I tried below , doesn't show any errors while compiling but get's the value 0 always

float f1;
.
.
scanf("%.3f",&f1);
printf("%3.3f\n",f1);  

回答1:


If you check the documentation, it says

scanf:

A format specifier for scanf follows this prototype:

%[*][width][length]specifier

and compare it to printf:

A format specifier follows this prototype:

%[flags][width][.precision][length]specifier

You will see, there is no precision field in scanf. So i guess rounding (or casting to int to cut the digits) is the only way.




回答2:


f1 = round( f1 * 1000.0 ) / 1000.0. scanf cannot help. BTW, use double instead of float.



来源:https://stackoverflow.com/questions/29095407/scanf-limit-decimal-places-while-reading

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