【问题标题】:OUTPUT ERROR,The problem is to find the sum 5000 digit number cpp [closed]输出错误,问题是找到总和5000位数字cpp [关闭]
【发布时间】:2020-10-24 12:01:36
【问题描述】:

这是代码(cpp)

    #include <iostream>
    #include <string>
    #include <numeric>//to import the accumulate function
    #include <vector>
    #include <algorithm>

    using namespace std;
    int main(){
    vector<long long> vi;
     string s; //this contains the long number its better not to type here
    int k=0,sum=0;
     for(int i=0;i<s.length();i++){
      k=(int)s[i]-(int)'0';
     cout<<k<<endl;
       vi.push_back(k);
 
      }
      for(int i:vi){
        cout<<i<<endl;
      }
         cout<<accumulate(vi.begin(),vi.end(),0);

    
        } 

无论我做什么,我都会得到答案 22660 我尝试使用不累积仍然 22660,我不知道为什么会发生这种情况

【问题讨论】:

  • 在不知道数字是多少的情况下,很难说出为什么会得到 22660。
  • 提示:将数字读取为字符串。访问数字,例如:int digit_value = number_as_string[x] - '0';
  • @cigien 对 5000 位求和不应溢出 int。
  • @ThomasMatthews 这就是他正在做的事情还是我错过了什么?
  • 为什么在隔离后将数字放入vector?为什么不直接将数字添加到 sum 变量中?

标签: c++ algorithm math stl


【解决方案1】:

我不明白你为什么使用std::vector。您可以在不使用向量的情况下计算总和:

int k=0,sum=0;
for(int i=0;i<s.length();i++)
{
    k = s[i]-'0';
    sum += k;
}

注意:如果您对总和值适合整数有点偏执,您可以使用unsigned integer,因为数字不能为负数。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 2021-11-27
    • 1970-01-01
    • 2023-01-11
    • 2021-11-12
    • 2023-03-27
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多