在5X表中最接近一个整数? [英] Round an Int to the Nearest in 5X Table?
问题描述
在我的iPhone应用程式中,我需要舍入一个整数到最接近的5的倍数。
第6轮至第10轮,第23轮至第25轮等。
希望您能帮忙,谢谢。
:
我做了一个巨大的忽视,忘记说了,我只想四舍五入!
如果你想总是四舍五入,你可以使用如下:
int a = 22;
int b =(a + 4)/ 5 * 5; // b = 25;
如果 a
应该如下向 int
中添加一个转型:
int b = (int)a + 4)/ 5 * 5; // b = 25;请注意,您可以使用函数 ceil
$ b <以完成相同的结果:
int a = 22;
int b = ceil((float)a / 5)* 5; // b = 25;
旧答案
要舍入到
5
最近的倍数,您可以执行以下操作:int a = 23;
int b =(int)(a + 2.5)/ 5 * 5;
In my iPhone app I need to round an integer to the nearest multiple of 5.
E.g. Round 6 to = 10 and round 23 to = 25 etc
Hope you can help, thanks.
EDIT:
I made a huge overlook, forgot to say, I only want to round up! In all situations, so 22 would round up to 25 for example.
解决方案If you want to always round up, you can use the following:
int a = 22; int b = (a + 4) / 5 * 5; // b = 25;
If
a
can be a float, you should add a cast toint
as follows:int b = ((int)a + 4) / 5 * 5; // b = 25;
Note that you can use the function
ceil
to accomplish the same result:int a = 22; int b = ceil((float)a / 5) * 5; // b = 25;
Old Answer:
To round to the nearest multiple of
5
, you can do the following:int a = 23; int b = (int)(a + 2.5) / 5 * 5;
这篇关于在5X表中最接近一个整数?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!