很简单,主要是刚学java,就直接贴代码了。
Rational.java
package hahaha;
public class Rational{
int numerator;//分子
int denominator;//分母
Rational(){
}
Rational(int a,int b){
if(a==0){
numerator=0;
denominator=1;
}
else{
setNumeratorDenominator(a,b);
}
}
void setNumeratorDenominator(int a,int b){
//设置分子和分母
int c=gcd(Math.abs(a),Math.abs(b));
numerator=a/c;
denominator=b/c;
if(numerator<0&&denominator<0){
numerator=-numerator;
denominator=-denominator;
}
}
int gcd(int a,int b){//求最大公约数
if(a<b){
int c=a;
a=b;
b=c;
}
int r=a%b;
while(r!=0){
a=b;
b=r;
r=a%b;
}
return b;
}
int getNumerator(){
return numerator;
}
int getDenominator(){
return denominator;
}
Rational add(Rational r){
//加法运算
int a=r.getNumerator();
int b=r.getDenominator();
int newNumerator=a*denominator+b*numerator;
int newDenominator=denominator*b;
Rational res=new Rational(newNumerator,newDenominator);
return res;
}
Rational sub(Rational r){
//减法运算
int a=r.getNumerator();
int b=r.getDenominator();
int newNumerator=b*numerator-a*denominator;
int newDenominator=b*denominator;
Rational res=new Rational(newNumerator,newDenominator);
return res;
}
Rational muti(Rational r){
//乘法运算
int a=r.getNumerator();
int b=r.getDenominator();
int newNumerator=a*numerator;
int newDenominator=b*denominator;
Rational res=new Rational(newNumerator,newDenominator);
return res;
}
Rational div(Rational r){
//除法运算
int a=r.getNumerator();
int b=r.getDenominator();
int newNumerator=b*numerator;
int newDenominator=a*denominator;
Rational res=new Rational(newNumerator,newDenominator);
return res;
}
}hahaha.java
package hahaha;
public class hahaha {
public static void main(String[] args) {
// TODO Auto-generated method stub
Rational r1=new Rational(1,5);
Rational r2=new Rational(3,2);
Rational r=r1.add(r2);
int a=r.getNumerator();
int b=r.getDenominator();
System.out.println("1/5+3/2="+a+"/"+b);
r=r1.sub(r2);
a=r.getNumerator();
b=r.getDenominator();
System.out.println("1/5+3/2="+a+"/"+b);
r=r1.muti(r2);
a=r.getNumerator();
b=r.getDenominator();
System.out.println("1/5+3/2="+a+"/"+b);
r=r1.div(r2);
a=r.getNumerator();
b=r.getDenominator();
System.out.println("1/5+3/2="+a+"/"+b);
int n=10,k=1;
System.out.println("计算2/1+3/2+5/3+8/5+……的前"+n+"项和.");
Rational sum=new Rational(0,1);
Rational item=new Rational(2,1);
while(k<=n){
sum=sum.add(item);
k++;
int fenzi=item.getNumerator();
int fenmu=item.getDenominator();
item.setNumeratorDenominator(fenzi+fenmu, fenzi);
}
a=sum.getNumerator();
b=sum.getDenominator();
System.out.println("用分数表示:");
System.out.println(a+"/"+b);
double res=(a*1.0)/b;
System.out.println("用小数表示:");
System.out.println(res);
}
}
1729

被折叠的 条评论
为什么被折叠?



