2

在我的 iPhone 应用程序中,我需要将一个整数四舍五入到最接近的 5 的倍数。

例如,第 6 轮到 = 10 和第 23 轮到 = 25 等

编辑

我忘了说,我只想围观!在所有情况下,例如,22 将四舍五入为 25。

4

7 回答 7

7

如果你想总是四舍五入,你可以使用以下内容:

int a = 22;
int b = (a + 4) / 5 * 5; // b = 25;

如果a可以是浮点数,则应按int如下方式添加强制转换:

int b = ((int)a + 4) / 5 * 5; // b = 25;

请注意,您可以使用该函数ceil来完成相同的结果:

int a = 22;
int b = ceil((float)a / 5) * 5; // b = 25;

老答案:

要四舍五入到 的最接近的倍数5,您可以执行以下操作:

int a = 23;
int b = (int)(a + 2.5) / 5 * 5;
于 2012-04-08T12:42:49.077 回答
4

采用 :

int rounded = (i%5==0) ? i : i+5-(i%5);

例子 :

    for (int i=1; i<25; i++)
    {
        int k= (i%5==0) ? i : i+5-(i%5);

        printf("i  : %d => rounded : %d\n",i,k);
    }

输出 :

i  : 1 => rounded : 5
i  : 2 => rounded : 5
i  : 3 => rounded : 5
i  : 4 => rounded : 5
i  : 5 => rounded : 5
i  : 6 => rounded : 10
i  : 7 => rounded : 10
i  : 8 => rounded : 10
i  : 9 => rounded : 10
i  : 10 => rounded : 10
i  : 11 => rounded : 15
i  : 12 => rounded : 15
i  : 13 => rounded : 15
i  : 14 => rounded : 15
i  : 15 => rounded : 15
i  : 16 => rounded : 20
i  : 17 => rounded : 20
i  : 18 => rounded : 20
i  : 19 => rounded : 20
i  : 20 => rounded : 20
i  : 21 => rounded : 25
i  : 22 => rounded : 25
i  : 23 => rounded : 25
i  : 24 => rounded : 25
于 2012-04-08T12:59:59.020 回答
2

斯威夫特 3

extension Int {
    func nearestFive() -> Int {
        return (self + 4) / 5 * 5
    }
}

采用

let a = 23.nearestFive()
print(a) // 25
于 2017-01-09T08:55:13.233 回答
1

对于整数解决方案,使用以 4 为偏的 mod 5 进行舍入:

int i;
int i5;

i = 6;
i5 = i + 4 - ((i+4) % 5);
NSLog(@"i: %i, i5: %i", i, i5);

i = 22;
i5 = i + 4 - ((i+4) % 5);
NSLog(@"i: %i, i5: %i", i, i5);
NSLog output:  

i: 6, i5: 10
i: 22, i5: 25

于 2012-04-08T12:48:42.403 回答
1

对于四舍五入到下一个 5 的倍数,例如,可以使用以下命令:

(int) (5.0 * ceil((number/5.0)))
于 2012-04-08T12:55:24.183 回答
1

你可能不需要这个问题的另一个答案,但我个人认为这更整洁:

int ans = ceil(input / 5.0) * 5.0;
于 2012-04-08T12:55:28.863 回答
0

由于您只需要四舍五入的整数,num+5-(num%5)就足够了。

旧答案

我对objective-c知之甚少,但这还不够。

r = num%5
r > 2 ? num+5-r : n-r
于 2012-04-08T12:41:41.857 回答