用JAVA编写1/2+1/3得出来的值
时间: 2024-11-17 07:30:25 浏览: 15
MessageDigestTestSHA1.rar_嵌入式/单片机/硬件编程_Java_
在Java中,你可以使用分数(Fraction)类或者数学库来计算两个分数相加的结果。这里我们可以手动创建一个简单的分数类来演示如何求解1/2 + 1/3。首先,我们需要创建一个`Fraction`类,然后实例化两个分数并相加。
```java
public class Fraction {
private int numerator;
private int denominator;
public Fraction(int numerator, int denominator) {
this.numerator = numerator;
this.denominator = denominator;
}
public Fraction add(Fraction other) {
int newNumerator = this.numerator * other.denominator + this.denominator * other.numerator;
int newDenominator = this.denominator * other.denominator;
return new Fraction(newNumerator, newDenominator);
}
@Override
public String toString() {
return numerator + "/" + denominator;
}
}
// 使用这个类来计算1/2 + 1/3
public static void main(String[] args) {
Fraction oneHalf = new Fraction(1, 2);
Fraction oneThird = new Fraction(1, 3);
Fraction sum = oneHalf.add(oneThird);
System.out.println("1/2 + 1/3 的结果是: " + sum);
}
```
当你运行这段代码,你会得到结果 `5/6`,即1/2 加上 1/3 等于 5/6。
阅读全文