C语言 很长的数用字符串数组如何求和

求一下高手帮我变一下,就是输入
111111111111111
111111111111111会输出
222222222222222的,最好用的简单点,我才刚刚学

#include <stdlib.h>

#include <stdio.h>

#include <string.h>


int main()

{

     char input1[256];

     char input2[256];

     char res[256];

     memset(input1,0,256);

     memset(input2,0,256);

     memset(res,0,256);

     scanf("%s", input1);

     scanf("%s", input2);


     int i = 255, j = 255;

     int y = 0;

     while ( i > -1 && j > -1)

     {

        if ( input1[i] == '\0' && input2[j] == '\0' )

         {

             i--;

             j--;

         }

         else if ( input1[i] != '\0' && input2[j] == '\0' )

         {

             j--;

         }

         else if (input1[i] == '\0' && input2[j] != '\0' )

         {

             i--;

         }

         else

         {

             int temp = (input1[i] - 48) + (input2[j] - 48) + y;

             y = temp / 10;

             res[ i > j ? i+1 : j+1 ] = temp % 10 + 48;

             i--;

             j--;

         }

     }


    if ( y > 0) res[0] = y + 48;


     printf("%s", y == 0 ? res + 1 : res);

     getchar();

     return 0;

}


温馨提示:答案为网友推荐,仅供参考
第1个回答  2013-10-24

这个在杭电的acm里专门的题型,就是大数运算,比如大数相加,想成,阶乘,。。。

我做过几以道。你说的这个比较简单。我AC过的。仔细看add函数。

#include <iostream>
#include <string>
using namespace std;
string add(string a,string b);
int main()
{
    string a,b;
    int N;
    cin >> N;
    for(int i= 1;i<=N;i++)
    {
        cin >> a >> b;
        cout<<"Case "<<i<<":"<<endl;
        cout<<a<<" + "<<b<<" = "<<add(a,b)<<endl;
        if(i<N) cout<<endl;
    }
    return 0;
}

string add(string a,string b)
{
    string max,min;
    max = (a.length() <= b.length())? b : a;
    min = (a.length() <= b.length())? a : b;
    int la = max.length();
    int lb = min.length();
    for(int i=la-1,j=lb-1;i>=0;i--,j--)
    {
        if(j>=0)
        {    
            max[i] = max[i] + (min[j] - '0');
        }
        else
            max[i] = max[i];
    }
    for(i=la-1;i>0;i--)
    {
        if(max[i] > '9')
        {
            max[i] -= 10;
            max[i-1]++;
        }
    }
    if(max[0] >'9')
    {
        max[0] -= 10;
        max = '1'+max;
    }
    return max;
}

第2个回答  2013-10-24
用数组将大数储存起来然后逐位相加,再输出数组元素即可追问

能具体编一下吗,能简单点吗

相关了解……

你可能感兴趣的内容

本站内容来自于网友发表,不代表本站立场,仅表示其个人看法,不对其真实性、正确性、有效性作任何的担保
相关事宜请发邮件给我们
© 非常风气网