public class myRational {
private int numerator;
private int denominator;
public myRational(int numerator,int denominator){
this.numerator=numerator;
this.denominator=denominator;
}
public void myRational(int x,int y){
if(y==0)
throw new RuntimeException("Division by zero");
if(x==0){
numerator=0;
denominator=1;
}else{
int g=gcd(Math.abs(x),Math.abs(y));
numerator=x/g;
denominator=Math.abs(y)/g;
if(y<0) numerator = -numerator;
}
}
public myRational add(myRational r){
return new myRational(this.numerator*r.denominator + r.numerator * this.denominator,this.denominator*r.denominator);
}
public myRational sub(myRational r){
return new myRational(this.numerator*r.denominator - r.numerator * this.denominator,this.denominator*r.denominator);
}
public myRational mul(myRational r){
return new myRational(this.numerator*r.numerator,this.denominator*r.denominator);
}
public myRational div(myRational r){
return new myRational(this.numerator*r.denominator,this.denominator*r.numerator);
}
public String toString(){
return numerator+"/"+denominator;
}
public int gcd(int x,int y){
int r=x%y;
while(r!=0){
x=y;
y=r;
r=x%y;
}
return y;
}
}
import java.util.Scanner;
public class TestmyRational {
public static void main(String[] args){
Scanner input=new Scanner(System.in);
System.out.println("enter a number: ");
double a=input.nextDouble();
System.out.println("转化后的分数: ");
System.out.println(dexToRational(a));
}
public static myRational dexToRational(double a){
int b=(int)a;
double y=a-b;
String s1=String.valueOf(y);
int len=s1.length()-2;
double ch=Math.pow(10,len);
int sh=(int)ch;
y=y*sh;
int p=(int)y;
int q=gcd(p,sh);
int m=p/q;
int n=sh/q;
m=b*n+m;
myRational r1=new myRational(m,n);
return r1;
}
public static int gcd(int x,int y){
int r=x%y;
while(r!=0){
x=y;
y=r;
r=x%y;
}
return y;
}
}