编写一个类,该类创建的对象可以计算等差数列的和java
时间: 2024-05-02 15:16:34 浏览: 82
以下是一个计算等差数列和的 Java 类示例:
```
public class ArithmeticProgression {
private int firstTerm;
private int commonDifference;
private int numberOfTerms;
public ArithmeticProgression(int firstTerm, int commonDifference, int numberOfTerms) {
this.firstTerm = firstTerm;
this.commonDifference = commonDifference;
this.numberOfTerms = numberOfTerms;
}
public int calculateSum() {
int sum = 0;
for (int i = 0; i < numberOfTerms; i++) {
sum += firstTerm + i * commonDifference;
}
return sum;
}
}
```
这个类有三个实例变量:`firstTerm` 表示等差数列的首项,`commonDifference` 表示公差,`numberOfTerms` 表示等差数列的项数。
构造函数在创建对象时初始化实例变量。`calculateSum` 方法使用 for 循环计算等差数列的和并返回结果。
以下是如何使用该类的示例:
```
ArithmeticProgression ap = new ArithmeticProgression(1, 2, 5);
int sum = ap.calculateSum();
System.out.println("Sum of the arithmetic progression: " + sum);
```
这将创建一个等差数列 1,3,5,7,9,并计算它们的和。输出应该是:
```
Sum of the arithmetic progression: 25
```
阅读全文