构造分数类页面
package com.lovo;
/**
* 分数类
* @author 骆昊
*
*/
public class Rational {
private int num; // 分子
private int den; // 分母
/**
* 构造器
* @param num 分子
* @param den 分母
*/
public Rational(int num, int den) {
this.num = num;
this.den = den;
normalize();
}
/**
* 构造器
* @param str 代表一个分数的字符串
*/
public Rational(String str) {
String[] s1 = str.split("/"); // 分子的字符串
String[] s2 = str.split("/"); // 分母的字符串
this.num = Integer.parseInt(s1[0]);
this.den = Integer.parseInt(s2[1]);
normalize();
}
/**
* 构造器
* @param x 一个小数
*/
public Rational(double x) {
this.num = (int) (x * 10000);
this.den = 10000;
simplify();
normalize();
}
/**
* public Rational add(Rational other) { ... }
* 访问修饰符 返回类型 方法名(参数列表) { ... }
* 加法
* @param other 另一个分数
* @return 两个分数相加的结果
*/
public Rational add(Rational other) {
return new Rational(this.num * other.den + this.den * other.num, this.den * other.den).normalize();
}
/**
* 减法
* @param other 另一个分数
* @return 两个分数相减的结果
*/
public Rational sub(Rational other) {
return new Rational(this.num * other.den - this.den * other.num, this.den * other.den).normalize();
}
/**
* 乘法
* @param other 另一个分数
* @return 两个分数相乘的结果
*/
public Rational mul(Rational other) {
return new Rational(this.num * other.num, this.den * other.den).normalize();
}
/**
* 除法
* @param other 另一个分数
* @return 两个分数相除的结果
*/
public Rational div(Rational other) {
return new Rational(this.num * other.den, this.den * other.num).normalize();
}
/**
* 化简
* @return 化简后的分数对象
*/
public Rational simplify() {
if(num != 0) {
int divisor = gcd(Math.abs(num),Math.abs(den));
num /= divisor;
den /= divisor;
}
return this;
}
/**
* 正规化
* @return 正规化以后的分数对象
*/
public Rational normalize() {
if(this.num == 0) {
this.den = 1;
}
else if(this.den < 0) {
this.den = - this.den;
this.num = - this.num;
}
return this;
}
/**
* 把对象按字符串打印出来
*/
public String toString() {
if(num==den){
return 1+"";
}
return num + (den != 1? ("/" + den) : "");
}
/**
* 公约数
* @param x
* @param y
* @return
*/
private int gcd(int x, int y) {
if(x > y) {
int temp = x;
x = y;
y = temp;
}
for(int i = x; i > 1; i--) {
if(x % i == 0 && y % i == 0) {
return i;
}
}
return 1;
}
}
package com.lovo;
import java.util.Scanner;
public class Test01 {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
System.out.print("r1 = ");
String str1 = sc.next();
Rational r2 = new Rational(2/4);
Rational r1 = new Rational(str1);
System.out.printf("%s + %s = %s\n", r1, r2, r1.add(r2).simplify());
System.out.printf("%s - %s = %s\n", r1, r2, r1.sub(r2).simplify());
System.out.printf("%s * %s = %s\n", r1, r2, r1.mul(r2).simplify());
System.out.printf("%s / %s = %s\n", r1, r2, r1.div(r2).simplify());
sc.close();
}
}