在我的iPhone應用程序中,我需要將整數調整爲5的最接近倍數。在5X表中最接近的一個Int?
E.g.第6輪= 10和第23輪= 25等
希望你能幫助,謝謝。
編輯:
我犯了一個巨大的俯瞰,忘了說了,我只是想圓了!在所有的情況下,例如22會湊到25。
在我的iPhone應用程序中,我需要將整數調整爲5的最接近倍數。在5X表中最接近的一個Int?
E.g.第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;
既然你只需要整數四捨五入,num+5-(num%5)
應該是足夠的。
老回答
我不知道很多關於Objective-C的,但不應該這樣就足夠了。
r = num%5
r > 2 ? num+5-r : n-r
對不起,我在我的問題做了一個愚蠢的錯誤,謝謝您的回答,我我改變了我的問題。 – 2012-04-08 12:46:56
那麼6呢?如果6應該舍入爲10,那麼應該再次編輯你的問題。如果是這樣的話,答案就會變成「num + 5-(num%5)」。 – Neal 2012-04-08 12:52:21
對於由4施力的整數溶液使用模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
對於舍入到的5的倍數,例如,下面可以使用:
(int) (5.0 * ceil((number/5.0)))
你可能不需要再回答這個問題,但我個人認爲這是整潔:
int ans = ceil(input/5.0) * 5.0;
用途:
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
你是個天才男人。 – 2013-06-10 15:00:37
斯威夫特3
extension Int {
func nearestFive() -> Int {
return (self + 4)/5 * 5
}
}
使用
let a = 23.nearestFive()
print(a) // 25
把(int)放在總和之前做什麼? – 2012-04-08 12:44:04
Doh,忘記提及一些關鍵信息。我總是想要回合,稍微修改我的問題。 (感謝您的回答!) – 2012-04-08 12:47:49
完美無缺,謝謝。 – 2012-04-08 12:55:34