问题描述
当我编写下面的代码时,我得到一个负数 (-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::accumulate
:https://en.cppreference.com/w/cpp/algorithm/accumulate 使用最后一个参数的类型进行计算。
你应该使用accumulate(v.begin(),v.end(),0ll);
,ll
使0
变成long long
,然后所有的计算都在long long
中完成,所以它不会溢出int
。