두 번째 논리 오류 println
문을 사용하면 아래 코드에서 무한 루프가 발생합니다.GCD 방법의 논리를 알아낼 수 없습니다
내가 알고있는 while 루프의 내부는 while 테스트가 true이므로 인쇄를 계속합니다. 48과 18을 각각 num1과 num2로 사용하면 GCD가 6이라는 정답을 얻을 수 있습니다. print out 문의 위치가 잘못되어 어디에 넣을 지 알 수 없습니다.
내 코드는 음수가 아닌 한 두 개의 정수로 이루어진 GCD를 찾습니다. 유클리드의 방법을 사용했습니다.
도움 주셔서 감사합니다.
import java.util.*;
public class Chapter5Lab_Problem1 {
public static void main(String[] args) {
Scanner console = new Scanner(System.in);
System.out.print("Type the first integer to find GCD");
int num1 = console.nextInt();
System.out.print("Type the second integer to find GCD ");
int num2 = console.nextInt();
gcd(num1,num2);
}
public static void gcd(int x, int y){
while(x >= 0 && y >= 0){
if(x == 0){
System.out.println("The GCD is " + y);
}
while(y != 0){
if(x > y){
x = x - y;
}else{
y = y - x;
}
}
System.out.println("The GCF is " + x);
}
}
}
입니다. – thang
정확하게 사용하는 방법을 모르고 있습니다. modulus를 대신 사용하여 메서드를 변경하는 방법을 보여줄 수 있습니까? – foodnliquor