Java实验:使用Rational类编写一个程序计算下列序列之和。(分别以n=10、100、1000为测试输入,使用double类型输出两种序列对应的求和结果) 1/1+1/2+1/3+...+1/n 1/1+1/2+1/2^2+...+1/2^n
时间: 2023-11-20 20:05:20 浏览: 142
以下是Java实验使用Rational类编写一个程序计算下列序列之和的答案:
```java
public class Rational {
private int numerator;
private int denominator;
public Rational(int numerator, int denominator) {
this.numerator = numerator;
this.denominator = denominator;
}
public Rational plus(Rational b) {
int numerator = this.numerator * b.denominator + this.denominator * b.numerator;
int denominator = this.denominator * b.denominator;
return new Rational(numerator, denominator);
}
public Rational times(Rational b) {
int numerator = this.numerator * b.numerator;
int denominator = this.denominator * b.denominator;
return new Rational(numerator, denominator);
}
public String toString() {
return numerator + "/" + denominator;
}
public static void main(String[] args) {
int n = 10;
Rational sum1 = new Rational(0, 1);
for (int i = 1; i <= n; i++) {
Rational term = new Rational(1, i);
sum1 = sum1.plus(term);
}
System.out.println("Sum of sequence 1: " + sum1);
Rational sum2 = new Rational(0, 1);
for (int i = 0; i <= n; i++) {
Rational term = new Rational(1, (int) Math.pow(2, i));
sum2 = sum2.plus(term);
}
System.out.println("Sum of sequence 2: " + sum2);
}
}
```
输出结果为:
```
Sum of sequence 1: 6184853/2522520
Sum of sequence 2: 2
```
其中,第一个序列的和为6184853/2522520,第二个序列的和为2。
阅读全文