实验题目四:
1. 程序源代码
package Rational;
public class Fraction{
private int sign;
private int numerator,denominator;
public Fraction(Fraction r){
sign=r.sign;
numerator=r.numerator;
denominator=r.denominator;
}
public Fraction(int n,int d){
sign=n*d>0?1:-1;
n=Math.abs(n);
d=Math.abs(d);
int t=gcd(n,d);
numerator=n/t;
denominator=d/t;
}
static int gcd(int m,int n){
int r=m%n;
while(r!=0){
m=n;
n=r;
r=m%n;
}
return n;
}
public Fraction add(Fraction r){
int d=denominator*r.denominator;
int n=sign*numerator*r.denominator+r.sign*r.numerator*denominator;
return new Fraction(n,d);
}
public Fraction minus(Fraction r){
int d=denominator*r.denominator;
int n=sign*numerator*r.denominator-r.sign*r.numerator*denominator;
return new Fraction(n,d);
}
public Fraction multiply(Fraction r){
int d=denominator*r.denominator;
int n=numerator*r.numerator;
int s=sign*r.sign;
return new Fraction(s*n,d);
}
public Fraction divide(Fraction r){
int d=denominator*r.numerator;
int n=numerator*r.denominator;
int s=sign*r.sign;
return new Fraction(s*n,d);
}
public void print(){
String str;
if(numerator==0)
System.out.println(numerator);
else if(numerator%denominator==0)
System.out.println(numerator/denominator);
else
{
str=sign*numerator+"/"+denominator;
System.out.println(str);
}
}
}
package Rational;
import java.util.*;
public class TestFraction{
public static void main(String arg[]){
Scanner sc =new Scanner(System.in);
System.out.print("请输入第一个分数fra1的分子:");
int n1=sc.nextInt();
System.out.println();
System.out.print("请输入第一个分数fra1的分母:");
int d1=sc.nextInt();
System.out.println();
System.out.print("请输入第二个分数fra2的分子:");
int n2=sc.nextInt();
System.out.println();
System.out.print("请输入第二个分数fra2的分母:");
int d2=sc.nextInt();
System.out.println();
Fraction fra1=new Fraction(n1,d1);
Fraction fra2=new Fraction(n2,d2);
Fraction fra3=fra1.add(fra2);
Fraction fra4=fra1.minus(fra2);
Fraction fra5=fra1.multiply(fra2);
Fraction fra6=fra1.divide(fra2);
System.out.print("第一个分数fra1=");fra1.print();
System.out.print("第二个分数fra2=");fra2.print();
System.out.print("两个分数的和fra1+fra2=");fra3.print();
System.out.print("两个分数的差fra1-fra2=");fra4.print();
System.out.print("两个分数的积fra1*fra2=");fra5.print();
System.out.print("两个分数的商fra1/fra2=");fra6.print();
}
}
2.试验结果