C语言四舍五入

/*使h中保留两位小数,并对第三位进行四舍五入
如h为1234.567,则函数返回123.570000
h为123.564,则返回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));
    }
}

四舍五入算法:如果要求精确到小数点后面的第n位,则需要对n+1位进行运算。
方法是将该小数乘10的n+1次方后加5,然后除10并强制转换为整数,
再将该数除10的n次方并强制转换为浮点数。

猜你喜欢

转载自www.cnblogs.com/zmmm/p/12728469.html