《quantitative finance with cpp》阅读笔记18---使用指针作为参数进行求和
作者:yunjinqi   类别:    日期:2024-01-01 09:40:12    阅读:128 次   消耗积分:0 分    

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;


版权所有,转载本站文章请注明出处:云子量化, http://www.woniunote.com/article/383
上一篇:《quantitative finance with cpp》阅读笔记17---给ContinuousTimeOption写接口并对KnockOutCallOption期权进行定价
下一篇:《quantitative finance with cpp》阅读笔记19---反转列表元素的顺序