import java.util.Scanner;
public class EuclidGCD {
public static void main(String[] args) {
Scanner kbd = new Scanner (System.in);
System.out.print ("Enter First Number: ");
int n1 = kbd.nextInt();
System.out.print ("Enter Second Number: ");
int n2 = kbd.nextInt();
int gcd = 1;
int k = 2;
while (k <= n1 && k <= n2){
if (n1 % k == 0 && n2 % k == 0)
gcd = k ;
k ++;
}
System.out.println("The GCD of " + n1 + " and " + n2 + " is " + gcd);
}
}
答案 0 :(得分:0)
只需添加一个if语句,检查n1和n2是否为正数,如果是,则只执行其余的代码。你不应该需要另一个while循环
public static void main(String[] args) {
Scanner kbd = new Scanner (System.in);
System.out.print ("Enter First Number: ");
int n1 = kbd.nextInt();
System.out.print ("Enter Second Number: ");
int n2 = kbd.nextInt();
if(n1 < 0 || n2 < 0 ){
System.out.println("POSITIVE NUMBERS ONLY ");
}else{
int gcd = 1;
int k = 2;
while (k <= n1 && k <= n2){
if (n1 % k == 0 && n2 % k == 0)
gcd = k ;
k ++;
}
System.out.println("The GCD of " + n1 + " and " + n2 + " is " + gcd);
}
}