分数(10分)
题目内容:
设计一个表示分数的类Fraction。这个类用两个int类型的变量分别表示分子和分母。
这个类的构造函数是:
Fraction(int a, int b)
构造一个a/b的分数。
这个类要提供以下的功能:
double toDouble();
将分数转换为double
Fraction plus(Fraction r);
将自己的分数和r的分数相加,产生一个新的Fraction的对象。注意小学四年级学过两个分数如何相加的哈。
Fraction multiply(Fraction r);
将自己的分数和r的分数相乘,产生一个新的Fraction的对象。
void print();
将自己以“分子/分母”的形式输出到标准输出,并带有回车换行。如果分数是1/1,应该输出1。当分子大于分母时,不需要提出整数部分,即31/30是一个正确的输出。
注意,在创建和做完运算后应该化简分数为最简形式。如2/4应该被化简为1/2。
你写的类要和以下的代码放在一起,并请勿修改这个代码:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35
| import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Fraction a = new Fraction(in.nextInt(), in.nextInt());
Fraction b = new Fraction(in.nextInt(),in.nextInt());
a.print();
b.print();
a.plus(b).print();
a.multiply(b).plus(new Fraction(5,6)).print();
a.print();
b.print();
in.close();
}
}
|
注意,你的类的定义应该这样开始:
class Fraction {
也就是说,在你的类的class前面不要有public。
输入格式:
程序运行时会得到四个数字,分别构成两个分数,依次是分子和分母。
输出格式:
输出一些算式。这些输入和输出都是由Main类的代码完成的,你的代码不要做输入和输出。
输入样例:
2 4 1 3
输出样例:
1/2
1/3
5/6
1
1/2
1/3
时间限制:500ms内存限制:32000kb
解答:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90
| import java.util.Scanner;
public class Main {
static class Fraction { private int x; private int y;
public Fraction(int a, int b) {
int i = Math.min(a, b); while (a % i != 0 || b % i != 0) { i--; } this.x = a / i; this.y = b / i;
}
double toDouble() {
double d; d = (double) x / y; return d;
}
Fraction plus(Fraction r) {
Fraction f1 = new Fraction(this.x * r.y + r.x * this.y, this.y * r.y); return f1;
}
Fraction multiply(Fraction r) {
Fraction f1 = new Fraction(this.x * r.x, this.y * r.y); return f1;
}
void print() {
if (x != y) { String printFraction; printFraction = this.x + "/" + this.y; System.out.println(printFraction); } else { System.out.println("1"); }
} }
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
Fraction a = new Fraction(in.nextInt(), in.nextInt());
Fraction b = new Fraction(in.nextInt(), in.nextInt());
a.print();
b.print();
a.plus(b).print();
a.multiply(b).plus(new Fraction(5, 6)).print();
a.print();
b.print();
in.close(); } }
|