mus*_*tze 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;
}
}
}
Run Code Online (Sandbox Code Playgroud)
tem*_*def 10
是的,这是有保证的.根据C ISO规范,§6.5.5/ 5:
/运算符的结果是第一个操作数除以第二个操作数的商;
1/2的商为0,因此1 / 2 == 0在C中保证为真.
希望这可以帮助!
| 归档时间: |
|
| 查看次数: |
517 次 |
| 最近记录: |