一维矩阵和

时间:2014-07-14 11:09:57

标签: c++ vector matrix

#include <iostream>
using namespace std;

int main () {
    int i;
    double scores[5]= {0.5,1.5,2.5,3.5,4.5};

    for(i = 0; i < 5; i++) {
        cout<<scores[i] << " ";
    }
    return 0;
}

我想知道如何在不使用scores[0]+scores[1]+scores[2]+scores[3]+scores[4];的情况下创建一条显示分数[5]中元素总和的行?

2 个答案:

答案 0 :(得分:1)

只计算沿途的总和:

#include <iostream>
using namespace std;

int main ()
{
    int i;
    double scores[5]= {0.5,1.5,2.5,3.5,4.5};
    double sum = 0.0;
    for(i=0;i<5;i++){
        cout << scores[i] << " ";
        sum += scores[i];
    }
    cout << sum << " ";

    return 0;
}

答案 1 :(得分:1)

使用std::accumulate

#include <algorithm>
//...
double sum = std::accumulate( std::begin(scores), std::end(scores), 0.0);

std::begin()std::end()需要C++11