问题
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