如何四舍五入到指定数字的最接近倍数? [英] How can I round up to the nearest multiple of the specified number?

查看:569
本文介绍了如何四舍五入到指定数字的最接近倍数?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我已经看过很多关于将数字四舍五入到最接近的倍数的问题,但是我对它们的方法不够了解,无法采用它们四舍五入到45,或者他们使用其他语言的特定语言方法。

I've looked at many questions regarding rounding up to the nearest multiple of a number, but I can't understand their methods well enough to adopt them for rounding up to 45 or they use language specific methods of other languages.

如果上述内容还没有多大意义,这里有一些更详细的解释:

Here is a bit more detailed explanation if the above doesn't make much sense yet:

示例输入:

int num1 = 67;
int num2 = 43;

预期结果:

>>round(num1) = 90
>>round(num2) = 45


推荐答案

足以添加缺少的 mod45

int upperround45(int i) {
    int temp = i%45;
    //For the algorithm we wish the rest to be how much more than last multiple of 45.
    if (temp < 0 ) 
        temp = 45 + temp;
    if (temp == 0) {
        return i;
    } else {
        return i + 45 - temp;
    }
}

编辑:

通常:

int upperround(int num, int base) {
    int temp = num%base;
    if (temp < 0 ) 
        temp = base + temp;
    if (temp == 0) 
        return num;
    return num + base - temp;

这篇关于如何四舍五入到指定数字的最接近倍数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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