Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
334 views
in Technique[技术] by (71.8m points)

c++ - Arrays - Sum Of Two numbers as arrays of digits

Take as input N, the size of array. Take N more inputs - digits between 0 and 9 - and store that in an array. Take as input M, the size of second array and take M more input digits and store that in second array. Write a function that returns the sum of the numbers represented by the two arrays. Print the value returned.

Input:

4

1 0 2 9

5

3 4 5 6 7

Output:

3, 5, 5, 9, 6, END

Below is the code I have written for it, but it's not giving any result rather it crashes.

using namespace std;
int main()
{
    int tsum,n,m,s,carry=0;
    cin>>n;
    int a[n],sum[]={0};
    for(int i=0; i<n; i++)
    {
        cin>>a[i];
    }
    cin>>m;
    int b[m];
    for(int i=0; i<m; i++)
    {
        cin>>b[i];
    }
    s=max(n,m);
    sum[s] = {0};
    while(n>0 and m>0)
    {
        tsum=a[n]+b[m]+carry;
        sum[s] = tsum%10;
        carry = tsum/10;
        n--;
        m--;
        s--;
    }
    if(n>m)
    {
        while(n>0)
        {
            tsum=a[n]+carry;
            sum[s] = tsum%10;
            carry = tsum/10;
            n--;
            s--;
        }
    }
    if(m>n)
    {
        while(m>0)
        {
            tsum=b[m]+carry;
            sum[s] = tsum%10;
            carry = tsum/10;
            m--;
            s--;
        }
    }
    

    for (int i=1; i<s; i++)
    {
        cout<<sum[i]<<", ";
    }
    cout<<"END";
    return 0;
}```
question from:https://stackoverflow.com/questions/65881418/arrays-sum-of-two-numbers-as-arrays-of-digits

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)
Waitting for answers

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...