/ * Make two decimal places in h and round the third digit. If h is 1234.567, the function returns 123.570000 h is 123.564, then it returns 123.560000 * / #include <stdio.h> #include <conio.h> # include <stdlib.h> float fun ( float h) { int temp = ( int ) (h * 1000 + 5 ) / 10 ; return ( float ) temp / 100.0 ; } void main () { float a; while (scanf ( " % f " , & a)! = { EOF) printf("%f\n",fun(a)); } }
Rounding algorithm: if you want to be accurate to the nth digit after the decimal point, you need to perform operations on n + 1 digits.
The method is to multiply the decimal by 10 to the power of n + 1 and add 5, then divide by 10 and force to convert to an integer,
then divide the number by 10 to the power of n and force to convert to floating point.