#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]中元素总和的行?
答案 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)
#include <algorithm>
//...
double sum = std::accumulate( std::begin(scores), std::end(scores), 0.0);
std::begin()
,std::end()
需要C++11