可能重複:
How can I check if multiplying two numbers in Java will cause an overflow?如何防止Java代碼中的整數溢出?
假設我有一個Java類方法,即用*
和+
操作。
int foo(int a, int b) { ... // some calculations with + and * }
如何確保foo
沒有發生溢出?
我想我可以用BigDecimal
或更換所有+和*與「包裝」,如:
int sum(int a, int b) { int c = a + b; if (a > 0 && b > 0 && c < 0) throw new MyOverfowException(a, b) return c; } int prod(int a, int b) { int c = a * b; if (a > 0 && b > 0 && c < 0) throw new MyOverfowException(a, b) return c; }
是否有更好的方式來確保沒有int
溢流出的Java方法發生?
你爲什麼要檢查它是否低於零?一個int可以低於0. – 11684
準確地說,這是一個int的範圍:-2,147,483,648到2,147,483,647 – 11684
你想鉗住這些值嗎? –