虽然循环不能正常工作:GCD,LCM

时间:2014-12-06 17:43:57

标签: while-loop greatest-common-divisor lcm

该程序用于查找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));
    }
}

错误:线程中的异常&#34; main&#34; java.lang.ArithmeticException:/ basic在BasicProgrammin.GCDLCM.main(GCDLCM.java:24)

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

1 个答案:

答案 0 :(得分:0)

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

如果你试图除以不小于零,那么跟随ERROR: Exception in thread "main" java.lang.ArithmeticException: / by zero异常发生,所以首先检查no是否大于0并尝试除去no.or使用try catch进行异常处理。

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

            a = b;
           try
       {  
           if(a>0)
        {  
               b = a % b;
         }
      }
     catch(Exception e )
     {
     System.out. print (e);
     } 
     } 
相关问题