c - 在 C 中,是否保证 1/2 == 0?

标签 c arrays math integer binary-search

<分区>

在 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 ISO 规范,§6.5.5/5:

The result of the / operator is the quotient from the division of the first operand by the second;

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

希望这对您有所帮助!

关于c - 在 C 中,是否保证 1/2 == 0?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19598608/

相关文章:

c - 如何在C程序中用汇编语言编写while循环\if语句?

c - 读取文本文件的完整内容后 fread() 失败

ruby - 在 Ruby 中合并和交错两个数组

javascript - 测试日期集合在哪些范围内不重叠

c - mingw32-gcc.exe : error: F: No such file or directory

c - 计算 ASCII 文件中换行符的最简单方法是什么?

C++ 两个矩阵的乘法

c++ - 在 C++ 中获取对象的数组索引

math - 三次贝塞尔曲线描边轮廓

r - 在 lapply 中操作函数