C中取整的有符号整数除法

问题描述 投票:0回答:2

我想计算x / y,其中x和y都是有符号整数,并得到四舍五入到最接近整数的结果。具体来说,我想要一个函数rquotient(x, y)这样:

ASSERT(rquotient(59, 4) == 15);
ASSERT(rquotient(59, -4) == -15);
ASSERT(rquotient(-59, 4) == -15);
ASSERT(rquotient(-59, -4) == 15);

ASSERT(rquotient(57, 4) == 14);
ASSERT(rquotient(57, -4) == -14);
ASSERT(rquotient(-57, 4) == -14);
ASSERT(iround(-57, -4) == 14);

我看过S.O.寻找解决方案,并发现以下内容(每个都有其缺点):

c signed integer-division
2个回答
0
投票

如果您知道x和y均为正:

int rquotient_uu(unsigned int x, unsigned int y) {
  return (x + y/2) / y;
}

如果您知道y为肯定值:

int rquotient_su(int x, unsigned int y) {
  if (x > 0) {
    return (x + y/2) / y;
  } else {
    return (x - y/2) / y;
  }
}

如果两个都签名:

int rquotient_ss(int x, int y) {
  if ((x ^ y) > 0) {             // beware of operator precedence
    return (x + y/2) / y;        // signs match, positive quotient
  } else {
    return (x - y/2) / y;        // signs differ, negative quotient
  }
}

并且,如果您真的想弄乱自己的未来自我或沉迷于打高尔夫球,请尝试此操作(但请抵抗这种冲动!):

int rquotient_ss(int x, int y) {
  return (x + (((x^y)>0)?y:-y)/2)/y;
}

0
投票

一个简单的解决方案是:

#include <math.h>

int rquotient(int const x, int const y) {
    return (int)round((double)x / y);
}
© www.soinside.com 2019 - 2024. All rights reserved.