gpt4 book ai didi

c - 在C中取整的有符号整数除法

转载 作者:行者123 更新时间:2023-12-03 13:47:39 25 4
gpt4 key购买 nike

我想计算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(rquotient(-57, -4) == 14);

我已经看过S.O.寻找解决方案,并发现以下内容(每个都有其缺点):
  • Rounding integer division (instead of truncating)(仅向上取整)
  • Integer division with rounding(仅x和y为正)
  • Round with integer division(仅x和y为正)
  • integer division, rounding(仅是y,但是在注释中有很好的建议)
  • Integer division rounding with negatives in C++(有关标准的问题,而非解决方案)
  • 最佳答案

    如果您知道xy都是肯定的:

    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
    }
    }

    而且,如果您真的想弄乱自己的 future 自我,或者沉迷于打高尔夫球,请抵制以这种方式编写的冲动:;)
    int rquotient_ss(int x, int y) {
    return (x + (((x^y)>=0)?y:-y)/2)/y;
    }

    关于c - 在C中取整的有符号整数除法,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/60009772/

    25 4 0
    Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
    广告合作:1813099741@qq.com 6ren.com