Java 除以零误差
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/2414250/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
divide by zero error
提问by David
here is the code (java):
这是代码(java):
class prime
{
public static boolean prime (int a, int b)
{
if (a == 0)
{
return false;
}
else if ((a%(b-1) == 0) && (b>2))
{
return false;
}
else if (b>1)
{
return (prime (a, b-1)) ;
}
else
{
return true;
}
}
public static void main (String[] arg)
{
System.out.println (prime (7, 7)) ;
}
}
This is the error message i get when i try to run it (it compiles fine):
这是我尝试运行它时收到的错误消息(编译正常):
Exception in thread "main" java.lang.ArithmeticException: / by zero
at prime.prime(prime.java:10)
at prime.prime(prime.java:16)
at prime.prime(prime.java:16)
at prime.prime(prime.java:16)
at prime.prime(prime.java:16)
at prime.prime(prime.java:16)
at prime.prime(prime.java:16)
at prime.main(prime.java:27)
So this means i devided by zero some how right? or does it mean something else? I don't see how i'm dividing by zero. What went wrong?
所以这意味着我除以零一些如何正确?还是其他意思?我不明白我是如何除以零的。什么地方出了错?
采纳答案by Tom
Try turning this around
尝试扭转这一局面
if ((a%(b-1) == 0) && (b>2))
to
到
if ((b>2) && a%(b-1)==0)
What's happening is that the a%(b-1)
operation is being executed before the b>2
test.
发生的事情是a%(b-1)
在b>2
测试之前正在执行操作。
After the switch, you are taking advantage of short-circuit evaluation. Once the b>2 test returns false, then there's no need to calculate the modulus (hence avoiding the division)
切换后,您正在利用短路评估。一旦 b>2 测试返回 false,则无需计算模数(因此避免除法)
回答by spender
I assume any code of the form x % 0
will throw this error. Your code does not guard against this possibility.
我假设表单的任何代码x % 0
都会抛出这个错误。您的代码不会防范这种可能性。
回答by Tom Castle
Because of your recursive call:
由于您的递归调用:
return (prime (a, b-1)) ;
You will at some point be calling prime with a value for b of 1. Which means on your second condition you will be testing a%0
. Since the modulo operator (%) is essentially a divide, that is bringing your divide by zero issue.
在某些时候,您将使用 b 的值为 1 来调用 prime。这意味着在您的第二个条件下,您将测试a%0
。由于模运算符 (%) 本质上是一个除法,这会导致您的除以零问题。
The solution is probably to catch this case to enforce b > 2 in your condition before doing the %.
解决方案可能是在执行 %.
回答by Alexandar Petrov
A % B = C
The Mathematical meaningof the %
is that you divide A
by B
and the reminder of this operation is C
. When B
is 0
you effectively ask : What is the reminder when we divide by zero ?. In mathematics though, division by zero is undefined and this is the reason for java.lang.ArithmeticException
数学意义的%
是,你把A
通过B
这种操作的提醒C
。如果B
是0
你有效问:什么是提醒,当我们除以零?但在数学中,除以零是未定义的,这就是原因java.lang.ArithmeticException