在C中,是否保证1/2 == 0? [英] In C, is it guaranteed that 1/2 == 0?
本文介绍了在C中,是否保证1/2 == 0?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
在C中保证 1/2 == 0
?我需要它来实现二进制搜索:
Is it guaranteed in C that 1/2 == 0
? I need that for an implementation of binary search:
/*
* 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:
Yes, this is guaranteed. According to the C ISO spec, §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,所以在C中保证1/2 <= 0
为真。
The quotient of 1 / 2 is 0, so 1 / 2 == 0
is guaranteed to be true in C.
希望这会有所帮助!
这篇关于在C中,是否保证1/2 == 0?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文