[英]Find closest number from uniform grid
I have an integer positive number n
. 我有一个整数正数n
。 Let's say n=5
for example. 例如,假设n=5
。 If we look at multiplies of n
, we see these numbers (let's call it n-grid) [... -15, -10, -5, 0, 5, 10, 15, ...]. 如果我们看n
倍数,就会看到这些数字(我们称其为n-grid)[... -15,-10,-5、0、5、10、15,...]。 Now I need to write a function F(n, N)
that, given an integer N
, outputs a closest number from that n-grid. 现在,我需要编写一个函数F(n, N)
,给定整数N
,该函数从该n网格输出最接近的数字。 For instance, F(n, 0) = 0
(for any n). 例如, F(n, 0) = 0
(对于任何n)。 F(5, 4) = 5
, F(5, 7) = 5
, F(5, 8) = 10
, F(5, -13) = -15
and so on. F(5, 4) = 5
, F(5, 7) = 5
, F(5, 8) = 10
, F(5, -13) = -15
等。
I've written this function: 我已经写了这个函数:
int const x = ((::abs(N) + (n / 2)) / n) * n;
if (N > 0)
{
return x;
}
else
{
return -x;
}
It seems to work but don't like how it looks. 它似乎有效,但不喜欢它的外观。 Can anybody suggest any improvement? 有人可以建议任何改善吗?
You could possibly get rid of the if
statement by multiplying x by (N/abs(N))
and returning the calculated value immeadiatelly, without even saving it in x
. 您可以通过将x乘以(N/abs(N))
并立即返回计算值来摆脱if
语句,甚至不将其保存在x
。
I would not do this however, because it would harm readability. 但是,我不会这样做,因为这会损害可读性。
here is simple math solution :- 这是简单的数学解决方案:
F(k,x) = (x/k)*k if abs(x-(x/k)*k) <= k/2
= (x/k)*k + sign(x)*k otherwise
C Implementation :- C实现:
#include<stdio.h>
#include<math.h>
int func(int k,int x) {
int a = (x/k)*k;
int sign = x/abs(x);
if(abs(x-a)<=k/2)
return(a);
else return(a+sign*k);
}
int main() {
printf("%d",func(5,121));
return 0;
}
int closest_number(int n,int N)
{
if(N==0)
return N;
else if(N > 0)
{
int temp = N % n;
if(temp > (n/2))
return (n*((N/n)+1));
else
return (n*(N/n));
}
else
{
int temp = N % n;
if(abs(temp) > (n/2))
return (n*((N/n)-1));
else
return (n*(N/n));
}
}
You can find the ideone output for the given set of test cases here http://ideone.com/NlJiPt 您可以在以下网址找到给定测试用例集的ideone输出: http: //ideone.com/NlJiPt
You are describing a rounding algorithm ; 您正在描述一种舍入算法 ; you need to specify whether rounding is symmetric or not, and then whether it is up or down (or toward/away from zero for symmetric). 您需要指定舍入是否对称,然后指定是向上还是向下(对于对称,朝向或远离零)。 ideone demo for below code. ideone演示下面的代码。
// F(4, 6) F(4, -6)
int symmetricTowardZero(int n, int N) {
return n * (int)(N / n); // 4 -4
}
int symmetricAwayFromZero(int n, int N) {
return n * (int)(N / n + (N < 0 ? -0.5 : +0.5)); // 8 -8
}
int unsymmetricDownward(int n, int N) {
return n * floor((double)N / n); // 4 -8
}
int unsymmetricUpward(int n, int N) {
return n * ceil((double)N / n); // 8 -4
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.