《Java语言程序设计》练习作业——求公约数

这不是技术贴,是记录贴,,,

1、求输入两个数的所有公约数,以及最大公约数,模块化代码实现。

完整代码如下所示:

import java.util.Scanner;

public class UintSixTest {	
	public static void main(String[] args) {
		// TODO Auto-generated method stub		
		Scanner input = new Scanner(System.in);
		System.out.print("input first number: ");
		int num1 = input.nextInt();
		System.out.print("input second number: ");
		int num2 = input.nextInt();
		
		System.out.print("\nfirst number is : " + num1 + 
				          "\nsecond number is : " + num2 +
				          "\ngcd = " + gcd(num1,num2));
	}
	
	public static int gcd(int m,int n) {
		int gcd = 1;
		int i = 2;
		while((i <= m) && (i <= n)) {
			if (m % i == 0 && n % i == 0) {
			        gcd = i;
				System.out.print("The value of i is = " + i + "\t");
			}	
			i++;
		}				
		return gcd;
	}
	
}

有过一点错误,就是 i++;一开始放在 if 条件里面,导致 i 不是连续累加。得到结果如下:

input first number: 12
input second number: 6
The value of i is = 2	The value of i is = 3	

i 的值跟着公约数在变,而不是累加,导致返回结果也不对。i++ 应该是在while循环里累加的,正常结果应该是:

input first number: 12
input second number: 6
The value of i is = 2	The value of i is = 3	The value of i is = 6	
first number is : 12
second number is : 6
gcd = 6

这就对了。 

 

 

你可能感兴趣的:(Java语言程序设计学习笔记,成长过程)