【问题标题】:Accumulate function in Vector (STL) giving negative sum向量中的累加函数(STL)给出负和
【发布时间】:2021-02-20 09:24:51
【问题描述】:

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

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

可能是什么原因?

【问题讨论】:

  • 溢出。文字0 具有int 类型,因此您对accumulate() 的使用通过将所有long long int 值添加到int 来将它们相加。 int(通常)可以表示较小范围的值 a long long,溢出一个会给出未定义的行为。将0 更改为0LL 以使accumulate() 给出long long int 类型的结果。

标签: c++ vector stl accumulate


【解决方案1】:

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

【讨论】:

  • 真正的代码有效,非常感谢,但我想问一下,“ll 将 0 变为 long long”究竟是什么意思? 0怎么能长这么长?
  • 文字有一个类型,所以0int,但0lllong long int
  • 我会推荐L,所以它看起来不像1
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2016-01-04
  • 1970-01-01
  • 2012-03-05
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多