向量 (STL) 中的累加函数给出负和

问题描述

当我编写下面的代码时,我得到一个负数 (-294967296)。

#include<iostream>
#include<vector>
#include<numeric>
using namespace std;
int main() {
    vector<long long int> v={1000000000,1000000000,1000000000};
    cout<<"Sum of all the elements are:"<<endl;
    cout<<accumulate(v.begin(),v.end(),0);
}

但是当我编写下面的代码时,我得到了一个正数 (2000000000)

#include<iostream>
#include<vector>
#include<numeric>
using namespace std;
int main() {
    vector<long long int> v={1000000000,0);
}

可能是什么原因?

解决方法

std::accumulatehttps://en.cppreference.com/w/cpp/algorithm/accumulate 使用最后一个参数的类型进行计算。

你应该使用accumulate(v.begin(),v.end(),0ll);ll使0变成long long,然后所有的计算都在long long中完成,所以它不会溢出int

示例:https://ideone.com/QQCYIW

相关问答

Selenium Web驱动程序和Java。元素在(x,y)点处不可单击。其...
Python-如何使用点“。” 访问字典成员?
Java 字符串是不可变的。到底是什么意思?
Java中的“ final”关键字如何工作?(我仍然可以修改对象。...
“loop:”在Java代码中。这是什么,为什么要编译?
java.lang.ClassNotFoundException:sun.jdbc.odbc.JdbcOdbc...