public class MathMethods {
public static int GCD (int a, int b){
int c;
int d;
d = -1;
if (a < 0 || b < 0){
return d;
}else{
while (b!=0){
c=a%b;
a=b;
b=c;
}
return a;
}
}
public static void main (String[] args){
System.out.println("GCD of 15 and 5: " + MathMethods.GCD(15,5));
System.out.println("GCD of 12 and 18: " + MathMethods.GCD(12,18));
System.out.println("GCD of 42 and 56: " + MathMethods.GCD(42,56));
System.out.println("GCD of 126 and 84: " + MathMethods.GCD(126,84));
System.out.println("GCD of 72390 and 15000: " + MathMethods.GCD(72390,15000));
}
}
我的GCD代码是正确的,因为我输入的数字会返回一个输出。但是我试图得到一个负数,然后输出负数1,但由于某种原因失败。