java的分数运算问题
发布网友
发布时间:2022-05-01 07:09
我来回答
共2个回答
热心网友
时间:2022-06-25 22:02
import java.util.Scanner;
public class Du{
public static void main(String args[]) throws Exception{
System.out.println("Please input a string in format xx/xx");
Scanner scanner = new Scanner(System.in);
String input = scanner.next();
String[] ary = input.split("/");
int numerator = Integer.parseInt(ary[0].trim());
int denominator = Integer.parseInt(ary[1].trim());
Fraction fra = new Fraction(numerator, denominator);
Fraction fra2 = new Fraction(15, 7);
Fraction fra3 = new Fraction(13, 12);
fra2.multiple(fra);//测试乘法
System.out.println("15/7 * 1/3 = " + fra2.toString());
fra.add(fra3);//测试加法
System.out.println("1/3 + 13/12 = " + fra.toString());
}
}
class Fraction{
private int numerator;//分子
private int denominator;//分母
public Fraction(int numerator, int denominator) throws Exception{
if(denominator == 0){//分母为0,出错
throw new Exception("Denominator can't be ZERO!");
}
this.numerator = numerator;
this.denominator = denominator;
}
public void multiple(Fraction fract2){//分数相乘
numerator *= fract2.numerator;//分子相乘
denominator *= fract2.denominator;//分母相乘
//结果约分
int lcd = getLCD(numerator, denominator);//最大公约数
numerator = numerator / lcd;
denominator = denominator /lcd;
}
public void add(Fraction fract2){
int gcm = getGCM(denominator, fract2.denominator);//最小公倍数作为分母
numerator *= gcm / denominator;//分子通分
fract2.numerator *= gcm / fract2.denominator;//第二个分子通分
numerator += fract2.numerator;//分子相加
denominator = gcm;//分母为最小公倍数
//约分
int lcd = getLCD(numerator, denominator);
if(lcd != 1){
numerator = numerator / lcd;
denominator = denominator / lcd;
}
}
public String toString(){
return numerator + "/" + denominator;
}
//求最大公约数
public static int getLCD(int num1, int num2){
int max = Math.max(num1, num2);
int min = Math.min(num1, num2);
while(max % min != 0){
int temp = max;
max = min;
min = temp % min;
}
return min;
}
//求最小公倍数
public static int getGCM(int num1, int num2){
return num1 * num2 /getLCD(num1, num2);
}
}
-----------------
Please input a string in format xx/xx
1/3
15/7 * 1/3 = 5/7
1/3 + 13/12 = 17/12
所有分数都可以通过乘10得倍数而达到分子和分母都是int类型的,所以没有问题的。
热心网友
时间:2022-06-25 22:03
这个题目是否需要需要考虑精度问题?是否需要考虑分子分母为分整数?如果需要的话上面的答案是有问题的。需要换一下2个参数类型。涉及到小数的加减乘除最好是用BigDecimal类型然后再转换