C++向量累积

Jos*_*osh 9 c++ vector accumulate

我试图使用累积函数的向量

vector <double> A;
double B = 0;

A.reserve(100);
for(itr = 0; itr < 210; itr++)
{
    term1 = pow(r[itr], 12);
    term1 = 1/term1;
    term2 = pow(r[itr], 6);
    term2 = 2/term2;
    A.push_back(term1 - term2);
}
B = accumulate(A.begin(), A.end(), 0);
Run Code Online (Sandbox Code Playgroud)

但是,我总是得到B = 0,而A有非零值

Ker*_* SB 24

std::accumulate在结果的类型是初始值的类型而不是容器元素的类型的意义上,有点偷偷摸摸!所以你的累加器会产生ints.

要解决这个问题,请累积到double:

accumulate(A.begin(), A.end(), 0.0);
//                             ^^^^^^^ literal of type double
Run Code Online (Sandbox Code Playgroud)