5

这是代码(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)) ; 
    }
}

这是我尝试运行它时收到的错误消息(它编译得很好):

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)

所以这意味着我除以零一些有多正确?还是有别的意思?我不明白我是如何除以零的。什么地方出了错?

4

4 回答 4

15

尝试扭转这种局面

if ((a%(b-1) == 0) && (b>2))

   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.

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)

于 2010-03-10T03:13:24.183 回答
2

由于您的递归调用:

return (prime (a, b-1)) ;

您将在某个时候调用 prime 的值 b 为 1。这意味着在您的第二个条件下,您将进行测试a%0。由于模运算符 (%) 本质上是一个除法,这会带来除以零的问题。

解决方案可能是在执行 %.

于 2010-03-10T03:12:37.420 回答
1
 A % B = C

The Mathematical meaning of 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

于 2018-09-12T17:17:21.713 回答
0

我假设任何形式的代码x % 0都会抛出这个错误。您的代码无法防范这种可能性。

于 2010-03-10T03:12:32.300 回答