1、定义一个分数类myRational类,数据成员:numerator:int(分子),denominator:int(分母),重写toString()方法:得到“分子/分母“的字符串,如:“123/

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;
		}
	}

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值