在5X表中最接近一个Int?

在我的iPhone应用程序中,我需要四舍五入到5的整数倍。

例如第6回合= 10和第23回合= 25等

希望你能帮忙,谢谢。

编辑:

我做了一个巨大的俯视,忘了说,我只想收起来! 在所有的情况下,例如22会凑到25。

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

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; 

使用 :

 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 

Swift 3

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

使用

 let a = 23.nearestFive() print(a) // 25 

为了凑到5的下一个倍数,例如,可以使用以下:

 (int) (5.0 * ceil((number/5.0))) 

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

 int ans = ceil(input / 5.0) * 5.0; 

对于一个整数解决scheme,使用mod 4偏移4来舍入:

 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: 

我:6,15:10
我:22,15:25

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

老答案

我不太了解Objective-C,但是这不应该是足够的。

 r = num%5 r > 2 ? num+5-r : nr