的java总之我怎么能知道是否需要携带
仅在加法和减法的情况下,当两个操作数都是正值且结果为负值时发生算术溢出,反之亦然。
class OverflowTest
{
public static void main (String[] args)
{
System.out.println(isOverflow((short)32767, (short)32767, '+'));
System.out.println(isOverflow((short)-32767, (short)-32767, '+'));
System.out.println(isOverflow((short)32767, (short)-32767, '+'));
}
private static boolean isOverflow(short a, short b, char op) {
short c = (op == '+') ? (short)(a+b) : (short)(a-b);
if((a > 0 && b > 0 && c < 0) || (a < 0 && b < 0 && c > 0))
return true;
return false;
}
}
文本解释是好的,但我真的不能跟随你的代码示例。 – Voo 2012-04-29 00:08:48
@Voo:你不明白什么? – blackcompe 2012-04-29 00:40:22
嗯,我要么省略这个例子,要么提供一个通用的例子。但是,只有当两个值都是正值时才起作用。这可能会导致更多的困惑,我想。 – Voo 2012-04-29 09:30:08
您可以使用更大的做加法或减法类型如int
,将其转换为short
,然后测试演员是否更改了该值。
int i = s1 + s2;
short s = (short)i;
if (i != s) { /* overflow */ }
实际上*任何*小于int值的算术运算无论如何都会扩展为int,所以我们不需要在那里进行int转换。 – Voo 2012-04-29 00:08:11
@Voo:好点,我删除了不必要的演员。 – 2012-04-29 00:09:54
携带和溢出是两个不同的东西! http://www.piclist.com/techref/method/math/c-vs-o.htm – 2012-04-30 15:51:00
...你在实施DCPU-16吗? – 2012-04-28 23:30:17
为什么你需要这样做? – 2012-04-28 23:37:04
我正在实现我自己的虚拟cpu(但很好猜猜Matti!) – 2012-04-30 15:50:05