最接近的整数 [英] Closest divisible integer
本文介绍了最接近的整数的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
示例.
int a = 254;
int b = 25;
int c = (closest integer to `a` that is divisible by `b`)
如何找到整数 c
?该示例的结果是 c = 250
.
How can I find the integer c
? The result of that example is c = 250
.
推荐答案
有两种情况需要考虑:
-
小于或等于
a
的最接近的整数:
int c1 = a - (a % b);
大于 a
的最接近的整数:
int c2 = (a + b) - (a % b);
然后我们需要检查哪个更接近 a
并返回:
Then we need to check which is closer to a
and return that:
int c;
if (a - c1 > c2 - a) {
c = c2;
} else {
c = c1;
}
因此我们可以创建一个 closestInteger()
方法,如下所示:
So we could create a closestInteger()
method like this:
static int closestInteger(int a, int b) {
int c1 = a - (a % b);
int c2 = (a + b) - (a % b);
if (a - c1 > c2 - a) {
return c2;
} else {
return c1;
}
}
示例:
System.out.println(closestInteger(254, 25));
System.out.println(closestInteger(9, 5));
输出:
250
10
这篇关于最接近的整数的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文