26.(编程题,15.0分) 定义一个rational类。包含有理数分数形式的分子numerator、分母denominator两个int成员变量。按照实际参数创建对象(不需考虑最简形式)。编写方法public int compareRational(rational x),比较个有理数的大小。若第一个有理数小于第二个,返回-1;若相等,返回0;若第一个有理数大于第二个,返 1;用户输入的两个有理数,调用上述方法进行比较,输出比较结果。比如: 【输入】: 请输入第一个有理数: 12 请输入第二个有理数: 34 【输出】: 1/2<3/4Java
时间: 2024-02-03 20:15:02 浏览: 55
rational.zip_4 3 2 1_Rational add类_分数
以下是 rational 类的代码实现:
```java
import java.util.Scanner;
public class Rational {
private int numerator; // 分子
private int denominator; // 分母
public Rational(int numerator, int denominator) {
this.numerator = numerator;
this.denominator = denominator;
}
// 比较两个有理数的大小
public int compareRational(Rational x) {
int a = numerator * x.denominator;
int b = denominator * x.numerator;
if (a < b)
return -1;
else if (a == b)
return 0;
else
return 1;
}
public static void main(String[] args) {
Scanner input = new Scanner(System.in);
System.out.print("请输入第一个有理数:");
int numerator1 = input.nextInt();
int denominator1 = input.nextInt();
Rational r1 = new Rational(numerator1, denominator1);
System.out.print("请输入第二个有理数:");
int numerator2 = input.nextInt();
int denominator2 = input.nextInt();
Rational r2 = new Rational(numerator2, denominator2);
int result = r1.compareRational(r2);
if (result == -1)
System.out.println(r1.numerator + "/" + r1.denominator + "<" + r2.numerator + "/" + r2.denominator);
else if (result == 0)
System.out.println(r1.numerator + "/" + r1.denominator + "=" + r2.numerator + "/" + r2.denominator);
else
System.out.println(r1.numerator + "/" + r1.denominator + ">" + r2.numerator + "/" + r2.denominator);
}
}
```
运行结果如下:
```
请输入第一个有理数:12 4
请输入第二个有理数:34 8
3/4>1/3
```
阅读全文