【问题标题】:In C, is it guaranteed that 1/2 == 0? [duplicate]在 C 中,是否保证 1/2 == 0? [复制]
【发布时间】:2013-11-05 02:08:29
【问题描述】:

在 C 中是否保证 1/2 == 0?我需要它来实现二进制搜索:

/*
 * len is the array length
 * ary is an array of ptrs
 * f is a compare function
 * found is a ptr to the found element in the array
 * both i and offset are unsigned integers, used as indexes
 */

for(i = len/2; !found && i < len; i += offset) {
    res = f(c->ary[i]);

    if (res == 0) {
        found = c->ary[i];
    }
    else {
        offset = (res < 0 ? -1 : 1) * (i/2);
        if (!offset) {
            i = len+1;
        }
    }
}

【问题讨论】:

    标签: c arrays math integer binary-search


    【解决方案1】:

    是的,这是有保证的。根据 C ISO 规范,§6.5.5/5:

    / 运算符的结果是第一个操作数除以 第二;

    1 / 2 的商为 0,因此在 C 中1 / 2 == 0 保证为真。

    希望这会有所帮助!

    【讨论】:

    • 我建议你以后不要回答明显的重复...
    • @H2CO3- 对不起...我没有意识到这是重复的。我实际上认为这真的很有趣,因为在我见过的每一个 C 实现中,我都知道除法是整数除法,但我不知道 C 规范是否保证了这一点。我希望这个答案能提供一个权威的参考,超越“它适用于我曾经尝试过的每个编译器。”
    • 公平点。标准保证了这一点,但请注意:这些简单的问题通常已经被问过和回答过,甚至多次。
    猜你喜欢
    • 1970-01-01
    • 2013-11-30
    • 1970-01-01
    • 1970-01-01
    • 2016-08-16
    • 2015-02-12
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多