您的位置:首页 > 编程语言

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

2017-05-26 14:58 309 查看
//题目:给出一个浮点数,输出它的分数形式。如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;
}

}


内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: