数学四舍五入函数与可变数字数

Math round function with variable number of digits

本文关键字:数字 函数 四舍五入      更新时间:2023-10-16

如何使用与excel round函数相同的数学round函数

float round( float arg );

round(number, num_digits)

  • 如果num_digits大于0,则将number四舍五入到指定的小数位数

  • 如果num_digits为0,则将数字四舍五入到最接近的整数

  • 如果num_digits小于0,则将数字四舍五入到小数点左边。

简单算术,

#include <stdio.h>
#include <cmath>
float my_round( float arg, int digits )
{
    float retValue = arg * pow(10.0f,(float)digits);
    retValue = round(retValue);
    return retValue * std::pow(10.0f,(float)-digits);
}

int main()
{
    float value = 12.3456789f;
    for(int i=-1;i<6;i++)
    {
            printf("%fn", my_round(value, i));
    }
}

应该可以做到这一点,(用g++编译)

输出为:

10.000000
12.000000
12.300000
12.349999
12.346001
12.345699
12.345679
相关文章: