编程之美2.6 精确表达浮点数

//题目:给出一个浮点数,输出它的分数形式。如0.285714(285714),输出2/7
//解法:公式推导,分别考虑小数非循环和循环部分的值,最后相加
public class Main {  
	  
    public static void main(String[] args) throws Exception {  
    	String input = "1.285714(285714)";
    	String result = getFloatNum(input);
    	System.out.println(result);
    }  
  
    public static String getFloatNum(String input){
    	int intValue = 0;							//整数部分的值
    	String firstStr = "";						//非循环小数部分
    	String secondStr = "";						//循环小数部分
    	if(input.charAt(0) != '0'){
    		intValue = input.charAt(0)-'0';
    	}
    	if(input.split("\\(").length == 1){
    		firstStr = input.substring(2);
    	}else{
    		firstStr = input.split("\\(")[0].substring(2);
    		secondStr = input.split("\\(")[1].substring(0,input.split("\\(")[1].length()-1);
    	}
    	int n = firstStr.length();					//非循环部分位数
    	int m = secondStr.length();					//循环部分位数
    	int value1 = Integer.parseInt(firstStr);	//非循环部分的数值
    	int value2 = 0;
    	if(secondStr != null || secondStr.length()!=0){
    		value2 = Integer.parseInt(secondStr);    	//如果没有循环部分就使value2为0
    	}
    	long num1 = (long)(intValue*Math.pow(10,n)*(Math.pow(10,m)-1))+(long)(value1*(Math.pow(10,m)-1))+value2;	//分子的值
    	long num2 = (long)(Math.pow(10,n)*(Math.pow(10,m)-1));		//分母的值
    	long gcd = getGcd(num1,num2);		//分子分母最大公约数
    	StringBuffer result = new StringBuffer();
    	result.append(String.valueOf(num1/gcd));	//分别化简分子分母并输出
    	result.append("/");
    	result.append(String.valueOf(num2/gcd));
    	return new String(result);
    }
    
    public static long getGcd(long num1, long num2){
    	long result = 1;
    	long temp = 2;
    	while(temp<=num1 && temp<=num2){		//约数大于两个数之一则停止循环
    		if(num1%temp == 0 && num2%temp == 0){		//每有一个能同时整数两个数的数就将其乘到result中
    			num1 = num1/temp;		//num1,num2分别除这个约数
    			num2 = num2/temp;
    			result = result*temp;
    		}else{
    			temp++;		//否则就递增约数    			
    		}
    	}
    	return result;
    }
  
}



  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值