第一次作业:计算“两个整数的最大公约数”程序

来源:互联网 发布:sql server企业管理器 编辑:程序博客网 时间:2024/05/22 07:42

同学代码:

void swap (int a, int b) {int c = a;a = b;b = c;}int gcd (int a, int b) {if (a == 0) {return b;}if (b == 0) {return a;}if (a > b) {swap(a, b);}int c;for (c = a%b; c>0; c=a%b) {a = b;b = c;}return b;}


题目:通过键盘输入两个整数、检查输入整数是否符合要求,并计算出其最大公约数。

代码:

import java.io.BufferedReader;import java.io.IOException;import java.io.InputStreamReader;public class GCD {private static BufferedReader bf = new BufferedReader(new InputStreamReader(System.in));public static void main(String[] args) {int[] values = new int[2];for (int i = 0; i < values.length; i++) {System.out.print("请输入一个整数:");values[i] = getValue();}System.out.println("最大公约数为:" + getGcd(values[0], values[1]));}public static int getGcd(int x, int y) {if (x < y) {int temp = x;x = y;y = temp;}if (x % y != 0) {x = x % y;y = getGcd(x, y);}return y;}private static int getValue() {int value = 0;try {String temp = bf.readLine();value = Integer.parseInt(temp);} catch (IOException e) {e.printStackTrace();} catch (NumberFormatException e){System.out.print("格式错误,请重新输入规范的整数数值:");value = getValue();}return value;}}

执行结果:



0 0
原创粉丝点击