多个分数的之间的操作,先完成下图分数输入与排序基本功能的程序(分数类的UML图可参考实验三,比较分数的大小必须用Comparable<T>接口或Comparator<T>接口)。排序要去掉相同的分数
时间: 2024-02-28 21:52:20 浏览: 31
好的,让我给您提供一个可能的Java代码实现:
```
import java.util.Arrays;
import java.util.Comparator;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
System.out.print("请输入分数的个数:");
int n = scanner.nextInt();
Fraction[] fractions = new Fraction[n];
for (int i = 0; i < n; i++) {
System.out.print("请输入第" + (i + 1) + "个分数的分子和分母,用空格隔开:");
int numerator = scanner.nextInt();
int denominator = scanner.nextInt();
fractions[i] = new Fraction(numerator, denominator);
}
Arrays.sort(fractions, new Comparator<Fraction>() {
@Override
public int compare(Fraction o1, Fraction o2) {
return o1.compareTo(o2);
}
});
int count = 0;
System.out.println("排序后去重的分数为:");
for (int i = 0; i < n; i++) {
if (i == 0 || !fractions[i].equals(fractions[i - 1])) {
System.out.println(fractions[i].toString());
count++;
}
}
System.out.println("去重后的分数个数为:" + count);
}
}
class Fraction implements Comparable<Fraction> {
private int numerator; // 分子
private int denominator; // 分母
public Fraction(int numerator, int denominator) {
this.numerator = numerator;
this.denominator = denominator;
simplify(); // 约分
}
private void simplify() {
int gcd = gcd(numerator, denominator); // 求最大公约数
numerator /= gcd;
denominator /= gcd;
}
private int gcd(int a, int b) {
int remainder = a % b;
while (remainder != 0) {
a = b;
b = remainder;
remainder = a % b;
}
return b;
}
@Override
public int compareTo(Fraction o) {
int result = numerator * o.denominator - o.numerator * denominator;
return result == 0 ? denominator - o.denominator : result;
}
@Override
public boolean equals(Object obj) {
if (obj instanceof Fraction) {
Fraction other = (Fraction) obj;
return numerator == other.numerator && denominator == other.denominator;
}
return false;
}
@Override
public String toString() {
return numerator + "/" + denominator;
}
}
```
这个程序与之前的程序基本相同,唯一的区别是加入了一个去重操作。具体实现方法是,在排序后的分数数组中遍历每一个分数,如果该分数和前一个分数相同,则不输出,否则输出该分数。通过这种方法,就可以去掉重复的分数了。
请注意,这个实现方式也只是其中一种可能的实现方式,您可以根据自己的需求和实际情况进行调整和优化。
阅读全文