Java实现1.0 = 1 / 1 1.5 = (1 + 2) / 2 2.0 = (1 + 2 + 3) / 3 2.5 = (1 + 2 + 3 + 4) / 4
时间: 2023-11-10 22:06:53 浏览: 74
runuo-2.4.1_2_runuo_attention1l7_RunUO2.4_
public class Fraction {
private int numerator;
private int denominator;
public Fraction(int numerator, int denominator) {
this.numerator = numerator;
this.denominator = denominator;
}
public static Fraction fromDouble(double value) {
int denominator = 1;
while (value != (int) value) {
value *= 10;
denominator *= 10;
}
int numerator = (int) value;
return new Fraction(numerator, denominator);
}
public Fraction add(Fraction other) {
int lcm = MathUtils.lcm(this.denominator, other.denominator);
int numerator1 = this.numerator * (lcm / this.denominator);
int numerator2 = other.numerator * (lcm / other.denominator);
int numerator = numerator1 + numerator2;
return new Fraction(numerator, lcm);
}
public Fraction divide(int divisor) {
return new Fraction(this.numerator, this.denominator * divisor);
}
public double toDouble() {
return (double) numerator / denominator;
}
public String toString() {
return numerator + "/" + denominator;
}
}
public class MathUtils {
public static int gcd(int a, int b) {
if (b == 0) {
return a;
}
return gcd(b, a % b);
}
public static int lcm(int a, int b) {
return (a * b) / gcd(a, b);
}
}
public class Main {
public static void main(String[] args) {
Fraction fraction1 = new Fraction(1, 1);
Fraction fraction2 = new Fraction(2, 2);
Fraction fraction3 = new Fraction(3, 3);
Fraction fraction4 = new Fraction(4, 4);
Fraction result1 = fraction1.divide(1);
Fraction result2 = fraction2.divide(2);
Fraction result3 = fraction3.divide(3);
Fraction result4 = fraction4.divide(4);
Fraction sum = result1.add(result2).add(result3).add(result4);
System.out.println(sum); // 输出 10/4
System.out.println(sum.toDouble()); // 输出 2.5
}
}
阅读全文