本文介绍了二进制搜索中mid =(beg + end)/2和mid = beg +(end-beg)/2有什么区别?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是C ++入门第五版问题3.26中的问题,我不知道它们之间的区别吗?可能是第二个可以避免溢出.

It is a problem from C++ primer fifth edition problem 3.26, I don't know the difference between them ?May be the second one can avoid overflow.

推荐答案

完全正确.不能保证beg+end是可表示的;但是在第二种情况下,中间值以及预期结果均不大于end,因此没有溢出的危险.

Exactly. There's no guarantee that beg+end is representable; but in the second case the intermediate values, as well as the expected result, are no larger than end, so there is no danger of overflow.

第二种形式也可以用于仿射类型,例如指针和其他随机访问迭代器,可以将它们减去以得出距离,但不能加在一起.

The second form can also be used for affine types like pointers and other random-access iterators, which can be subtracted to give a distance, but not added together.

这篇关于二进制搜索中mid =(beg + end)/2和mid = beg +(end-beg)/2有什么区别?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

06-12 23:51