本文介绍了这个条件是否足以满足乘法运算中的溢出检查的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

    int isOverflow(uint a, uint b) {
        // a and b are unsigned non-zero integers.
        uint c = a * b;

        if (c < ( a > b ? a : b))
                return 1;
        else
                return 0;
}

我想念什么吗?我认为上面的代码片段会起作用.

Am I missing something ? I think the above snippet will work.

编辑:我看过其他解决方案,例如,其中使用了一些奇特的方法对其进行检查.但是对我来说,简单的解决方案也看起来是正确的.这就是为什么我问这个问题.

EDIT : I have seen other solutions like multiplication of large numbers, how to catch overflow which uses some fancy methods to check it. But to me above simple solution also looks correct. Thats why I am asking this question.

推荐答案

很容易通过发现异常来证明这是错误的:

It's easy to prove this is wrong by finding an exception:

请考虑以下两个8位无符号值:a = 0x1Fb = 0xF.

Consider these two 8-bit unsigned values: a = 0x1F and b = 0xF.

c = a * b
c = 0x1F * 0xF
c = 0xD1              (Overflow! The real answer is 0x1D1)

c < ( a > b ? a : b)
0xD1 < 0x1F           => False  (Wrong!)

正确的答案是此处.

这篇关于这个条件是否足以满足乘法运算中的溢出检查的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

08-15 17:00