数位数可变的数学舍入函数 [英] Math round function with variable number of digits

查看:67
本文介绍了数位数可变的数学舍入函数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

How can I use the math round function same as excel round function

float round( float arg );

回合(数字,位数)

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

  • If num_digits is greater than 0, then number is rounded to the specified number of decimal places.

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

If num_digits is 0, the number is rounded to the nearest integer.

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

If num_digits is less than 0, the number is rounded to the left of the decimal point.

推荐答案

简单算术

#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("%f\n", my_round(value, i));
    }
}

应该做到这一点,(与g ++一起编译)

should do the trick, (compiled with g++)

输出为:

10.000000
12.000000
12.300000
12.349999
12.346001
12.345699
12.345679

这篇关于数位数可变的数学舍入函数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆