Write a function sumDoubles which takes a pointer to a list of doubles and the length of the list and returns the total. Write a test for this function.
使用cpp计算序列的求和方式有很多种,这是一种相对高效一些的方式,比直接for循环数据来说。下面的代码仅供参考。
double sumUsingList(double* begin, int length) {
double sum = 0.0;
double* end = begin + length;
for (double* ptr = begin; ptr != end; ptr++) {
sum += *ptr;
}
return sum;
}
void testSumUsingList() {
int n = 10;
double* nSquares = new double[n];
for (int i = 0; i < n; i++) {
nSquares[i] = i*1.0;
}
double sum6 = sumUsingList(nSquares, n);
cout << "sum6=" << sum6 << "\n";
ASSERT_APPROX_EQUAL(sum6, 45, 0.00001);
delete[] nSquares;
系统当前共有 481 篇文章