gpt4 book ai didi

java - 如何编写一个程序,将整数序列读入数组并计算数组中所有元素的交替和?

转载 作者:行者123 更新时间:2023-12-01 17:31:56 25 4
gpt4 key购买 nike

编写一个程序,将整数序列读入数组,并计算数组中所有元素的交替和。例如,如果程序使用输入数据执行

1 4 9 16 9 7 4 9 11然后它计算

1 - 4 + 9 - 16 + 9 - 7 + 4 - 9 + 11 = - 2

到目前为止我有以下代码:

import java.util.Arrays;

/**
This class computes the alternating sum
of a set of data values.
*/
public class DataSet
{
private double[] data;
private int dataSize;

/**
Constructs an empty data set.
*/
public DataSet()
{
final int DATA_LENGTH = 100;
data = new double[DATA_LENGTH];
dataSize = 0;
}

/**
Adds a data value to the data set.
@param x a data value
*/
public void add(double x)
{
if (dataSize == data.length)
data = Arrays.copyOf(data, 2 * data.length);
data[dataSize] = x;
dataSize++;
}

/**
Gets the alternating sum of the added data.
@return sum the sum of the alternating data or 0 if no data has been added
*/
public double alternatingSum()
{
. . .
}
}

我必须使用以下类作为测试器类:

/**
This program calculates an alternating sum.
*/
public class AlternatingSumTester
{
public static void main(String[] args)
{
DataSet data = new DataSet();

data.add(1);
data.add(4);
data.add(9);
data.add(16);
data.add(9);
data.add(7);
data.add(4);
data.add(9);
data.add(11);

double sum = data.alternatingSum();
System.out.println("Alternating Sum: " + sum);
System.out.println("Expected: -2.0");
}
}

最佳答案

我为你实现了alternatingSum方法:

public double alternatingSum() {
double alternatingSum = 0;
if(data != null || dataSize > 0) {
for(int i = 0; i < dataSize; i = i + 2) {
alternatingSum += data[i];
}
for(int i = 1; i < dataSize; i = i + 2) {
alternatingSum -= data[i];
}
}
return alternatingSum;
}

关于java - 如何编写一个程序,将整数序列读入数组并计算数组中所有元素的交替和?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10052568/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com