0

该程序用于查找 GCD、LCM。当程序到达while循环时我遇到了问题。我的代码如下。

public class GCDLCM {

    public static void main(String[] args) {

        Scanner sc = new Scanner(System.in);
        int x = sc.nextInt();
        int y = sc.nextInt();
        int a,b;
        if(x < y) {

            a = y;
            b = x;  
            while((a % b) != 0) {

                a = b;
                b = a % b;
            }
            System.out.println("GCD: "+b);
        }
        else {

            a = x;
            b = y;
            while((a % b) != 0) {

                a = b;
                b = a % b;
            }
            System.out.println("GCD: "+b);
        }

        System.out.println("LCM: "+((x * y)/b));
    }
}

错误:线程“主”java.lang.ArithmeticException 中的异常:/在 basicProgrammin.GCDLCM.main(GCDLCM.java:24) 处为零

请帮助我,为什么我的while循环不起作用?提前致谢。

4

1 回答 1

0

您可以使用try catch. 这是程序的异常。异常是程序的逻辑运行时错误。使用try catch您可以处理异常。no 不允许除以零,请检查 no 是否大于零。

如果您尝试除数不小于零, ERROR: Exception in thread "main" java.lang.ArithmeticException: / by zero则会发生以下异常,因此首先检查 no 是否大于 0 并尝试除数。或使用 try catch 进行异常处理。

    while((a % b) != 0) {

            a = b;
           try
       {  
           if(a>0)
        {  
               b = a % b;
         }
      }
     catch(Exception e )
     {
     System.out. print (e);
     } 
     } 
于 2014-12-06T18:01:19.527 回答