该表示分数的类在构造对象时接收两个整数分别作为分子和分母,为了便于进行运算,还需要将其进行约分。
import java.util.Scanner;
import java.lang.String;
class Fraction{
int c;
int m;
double dec;
Fraction(int a, int b){ //构造并约分
int gcd = Gcd(a,b);
this.c = a / gcd;
this.m = b / gcd;
}
static int Gcd(int x, int y){
return y == 0 ? x : Gcd(y, x % y);
}
double toDouble(){
this.dec = (double)(this.c) / (double)(this.m);
return this.dec;
}
public Fraction add(Fraction other){
int res_c, res_m;
res_c = other.c * this.m + this.c * other.m;
res_m = other.m * this.m;
return new Fraction(res_c,res_m);
}
public Fraction multiply(Fraction other){
int res_c, res_m;
res_c = other.c * this.c;
res_m = other.m * this.m;
return new Fraction(res_c,res_m);
}
@Override
public String toString(){
if(this.c % this.m == 0){
return String.valueOf((this.c / this.m));
}
else{
return String.valueOf(this.c) + "/" + String.valueOf(this.m);
}
}
}
public class Main {
public static void main(String[] args) {
Scanner sc = new Scanner(System.in);
int fz, fm;
System.out.println("first number,fenzi fenmu");
fz = sc.nextInt();
fm = sc.nextInt();
Fraction f1 = new Fraction(fz, fm);
System.out.println("second number,fenzi fenmu");
fz = sc.nextInt();
fm = sc.nextInt();
Fraction f2 = new Fraction(fz, fm);
System.out.println("first Fraction:" + f1);
System.out.printf("first output as double:%.2f\n", f1.toDouble());
System.out.println("second Fraction:" + f2);
System.out.printf("second output as double:%.2f\n", f2.toDouble());
System.out.println("result of two Fraction add:" + f1.add(f2));
System.out.println("result of two Fraction multiply:" + f1.multiply(f2));
sc.close();
}
}
运行结果: