使用指针添加大数字(c ++)

时间:2015-08-01 10:16:54

标签: c++ string pointers

我需要帮助,下面的代码不起作用,因为它在运行时没有返回任何内容。我正在尝试添加大数字以至于数字无法在标准C ++整数数据结构中表示

mission.cpp

void Big2Add(const char * num1, const char * num2, char * result)
    {
        string a = num1;
        string b = num2;
        int min = (a.length() < b.length() ? a.length():b.length());
       int max = (a.length() < b.length() ? b.length():a.length());

       int *n1 = new int[max];
       int *n2 = new int[max];

       for (unsigned int i=0; i < a.length(); i++)
       {
          n1[i] = a.at(a.length() - 1 -i) - 48;
       }

       cout << a << endl;

       for (unsigned int i=0; i < b.length(); i++)
       {
          n2[i] = b.at(b.length()-1 -i) - 48;
       }

       cout << b << endl;

       int carry = 0;

       int* sum = new int[max];

       int k=0;
       for (k = 0; k < max; k++)
       {
          sum[k] = (n1[k] + n2[k] + carry) % 10;

          if ( (n1[k] + n2[k] + carry) >= 10)
             carry = 1;
          else carry = 0;
       }
       sum[max] = carry;

       for (int j= max; j >= 0; j--)
       {

            *result = sum[j];
          }
       }

的main.cpp

 char result[10];
        const char * num1 = "10";
        const char * num2 = "10";
        Big2Add(num1, num2, result);
        cout << "Part 3" << endl;
        cout << "The addition of " << num1 << " and " << num2 << " is " <<     result << endl;
        cout << endl;

2 个答案:

答案 0 :(得分:1)

第一个明显的错误:

   int* sum = new int[max];

...

   sum[max] = carry;

您需要分配max + 1才能使用最大位置

第二个和第三个明显的错误:

    *result = sum[j];

您忘了提前结果而忘记添加'0'

第四,你忘了null终止字符串。

尝试:

   for (int j= max; j >= 0; j--)
   {

        *(result++) = sum[j] + '0';
   }
   *result = 0;

答案 1 :(得分:0)

好吧它现在可以工作但是我现在的主要问题是,如果我说10加10它会给我010或100 10它会给我0110但是我的答案前面还有一个额外的零如果我加99而99则会给出198 y?

void Big2Add(const char * num1, const char * num2, char * result)
    {

        string a = num1;
        string b = num2;
       int max = (a.length() < b.length() ? b.length():a.length());

       int *n1 = new int[max];
       int *n2 = new int[max];

       unsigned int i;
        for (i=0; i < a.length(); i++)
        {
            n1[i] = a.at(a.length() - 1 -i) - 48;
        }
        for (int j = i; j < max; ++j) 
        {
            n1[j] = 0;
        }



        for (i=0; i < b.length(); i++)
        {
            n2[i] = b.at(b.length()-1 -i) - 48;
        }
        for (int j = i; j < max; ++j) 
        {
            n2[j] = 0;
        }

       int carry = 0;


       int* sum = new int[max];

       int k=0;

       for (k = 0; k < max; k++)
       {
          sum[k] = (n1[k] + n2[k] + carry) % 10;

          if ( (n1[k] + n2[k] + carry) >= 10)
             carry = 1;
          else carry = 0;
       }
       sum[max] = carry;


       for (int j= max ; j >= 0; j--)
       {
            if(sum[0] == 0)
            {

            }
            *(result++) = sum[j] + '0';
       }


       *result = 0;
    }