在C ++中找到最接近n且可被m整除的数字
假设我们有两个整数n和m。我们必须找到最接近n的数字并除以m。如果有多个这样的数字,则显示最大绝对值的数字。如果n可被m整除,则返回n。因此,如果n=13,m=4,则输出为12。
为了解决这个问题,我们可以按照以下步骤进行:
令q:=n/m,n1:=m*q
如果n*m>0,则n2:=m*(q+1),否则n2:=m*(q-1)
如果|n–n1|<|n–n2|,然后返回n1,否则返回n2
示例
#include<iostream> #include<cmath> using namespace std; int findClosest(int n, int m) { int q = n / m; int n1 = m * q; int n2 = (n * m) > 0 ? (m * (q + 1)) : (m * (q - 1)); if (abs(n - n1) < abs(n - n2)) return n1; return n2; } int main() { int n = 13, m = 4; cout << "Closest for n = " << n << ", and m = " << m << ": " << findClosest(n, m) << endl; n = 0; m = 8; cout << "Closest for n = " << n << ", and m = " << m << ": " << findClosest(n, m) << endl; n = 18; m = -7; cout << "Closest for n = " << n << ", and m = " << m << ": " << findClosest(n, m) << endl; }
输出结果
Closest for n = 13, and m = 4: 12 Closest for n = 0, and m = 8: 0 Closest for n = 18, and m = -7: 21