简体   繁体   English

整数数组中每个元素的位数之和

[英]Sum of digits of each elements inside an array of integers

I want to calculate the sum of digits in each elements in array.我想计算数组中每个元素的数字总和。 The problem is with this code it only calculates the the sum of odd indexes (1,3,5...) in array.问题在于这段代码只计算数组中奇数索引 (1,3,5...) 的总和。 And in console it shows some random numbers for even indexes (0,2,4...)在控制台中,它显示了偶数索引的一些随机数(0,2,4 ...)

Can anybody tell me what is the problem?谁能告诉我有什么问题?

And yes I need to use it as array是的,我需要将它用作数组

Here are output values:以下是 output 值:

Enter how many numbers you want to calculate sum of digits: 5
Enter those numbers: 12
Enter those numbers: 33
Enter those numbers: 44
Enter those numbers: 22
Enter those numbers: 33
Sum of 0 number is: 4
Sum of 1 number is: 6
Sum of 2 number is: 40
Sum of 3 number is: 4
Sum of 4 number is: 11730950
#include <iostream>


int main(int argc, char** argv) 
{
    int n;
    int temp;
    int pom;

    cout << "Enter how many numbers you want to calculate sum of digits: ";
    cin >> n;

    int numbers[n];
    int sum[n];

    for (int i = 0; i < n; i++)
    {
        cout << "Enter those numbers: ";
        cin >> numbers[i];
    }

    for (int i = 0; i < n; i++)
    {
        while (numbers[i] > 0)
        {
        temp = numbers[i] % 10;
        sum[i]+= temp;
        numbers[i] = numbers[i]/10; 
        }

    }



    for (int i = 0; i < n; i++)
    {
        cout << "Sum of " << i << " number is: " << sum[i] << endl;
    }

    return 0;
}

You need to initialize the sum array, like this:您需要初始化sum数组,如下所示:

int sum[n] {};

otherwise, the first time you read from an element of sum you have undefined behaviour.否则,您第一次从 sum 的元素中sum时,您的行为未定义。

Also, variable length arrays are not part of standard c++.此外,可变长度 arrays 不是标准 c++ 的一部分。 If you don't know the size of the array at compile time, just use a std::vector .如果您在编译时不知道数组的大小,只需使用std::vector

If you absolutely must use an array, then you will need to dynamically allocate it, like this:如果您绝对必须使用数组,那么您将需要动态分配它,如下所示:

int * arr = new int[n]{};
#include <iostream>
using namespace std;
int main() {
    int a,temp,sum=0;
    cin>>a;
    int arr[a];
    for(int i=0;i<a;i++)
    {
        cin>>arr[i];
    }
    for(int i=0;i<a;i++)
    {
        sum=0;
        while(arr[i]>0)
        {
            temp=arr[i]%10;
            sum+=temp;
            arr[i]=arr[i]/10;
        }
        cout<<sum<<" ";
    }

}

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM