4/28/2011

Greatest Common Divisor

話說這回的作業是上研究所課程以來第三次的程式作業,內容只有這一小部份跟之前不一樣,卻大大加長了我寫爪哇作業的時間,只能說接下來的這一個半月還得跟爪哇做好朋友,爪哇~我要每天多認識你一點一點呀!



這次作業主要是請玩家輸入兩個數字,然後求這兩個入字的最大公因數。

// import class
import java.util.Scanner;

public class CH04PR43
{
public static void main(String[] args)
{
// Welcome the user to come to the program
System.out.println("Greatest Common Divisor Finder");
System.out.println();

Scanner sc = new Scanner(System.in);
String choice = "y";

while (choice.equalsIgnoreCase("y"))
{
// Get numbers from the user
System.out.print("Enter first number:  ");
int firstNumber = sc.nextInt();
System.out.print("Enter second number:  ");
int secondNumber = sc.nextInt();

// do algorithm
int temp = 0;
while (secondNumber!=0)
{
temp = firstNumber % secondNumber;
firstNumber = secondNumber;
secondNumber = temp;
}
System.out.println("Greatest Common Divisor: " + firstNumber);
System.out.println();

// see if the user want to continue
System.out.print("Continue? (y/n): ");
choice = sc.next();
System.out.println();
     }
}
}

No comments:

Post a Comment