java编写程序,从控制台读入一个分数的分子和分母(分数无符号,并且分子小于分母,其大小不会超过int数据类型的表示范围),输出化简后分子和分母不含公约数的分数。
时间: 2024-06-11 07:03:58 浏览: 132
```java
import java.util.Scanner;
public class FractionSimplifier {
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("Enter the numerator: ");
int numerator = input.nextInt();
System.out.print("Enter the denominator: ");
int denominator = input.nextInt();
// find the greatest common divisor
int gcd = findGCD(numerator, denominator);
// simplify the fraction
numerator /= gcd;
denominator /= gcd;
System.out.println("The simplified fraction is: " + numerator + "/" + denominator);
}
/**
* Find the greatest common divisor of two numbers using Euclid's algorithm
* @param a the first number
* @param b the second number
* @return the greatest common divisor
*/
public static int findGCD(int a, int b) {
if (b == 0) {
return a;
} else {
return findGCD(b, a % b);
}
}
}
```
注意,我们使用了递归算法来求最大公约数。如果不熟悉递归,可以先学习递归的概念和原理。
阅读全文