Charles_Su 2016-03-31 16:18 采纳率: 21.4%
浏览 1277

大整数加法,我的代码问题出在哪里,为什么不能运行?

#include
#include
using namespace std;
class INT
{
char *p_num;
int len;
public:
//构造函数
INT()
{
p_num = NULL; len = 0;
}
INT(const char *p)
{
len = strlen(p)+1;
p_num=new char[strlen(p)+1];
strcpy(p_num,p);
}//拷贝函数
INT(const INT &s)
{
len = s.len;
p_num=new char[strlen(s.p_num)+1];
strcpy(p_num,s.p_num);
}

//赋值函数
INT & operator=(const INT &s)
{

    delete[]p_num;
    len = s.len;
    p_num = new char[strlen(s.p_num) + 1];
    strcpy(p_num, s.p_num);
    return *this;
}
//析构函数
~INT()
{
    delete []p_num;
    p_num=NULL;
    len = 0;
}
//下面三个重载函数实现INT型与int型混合运算
friend INT operator+(const INT &x1, const INT &x2);
friend INT operator+(const INT &x, int y);
friend INT operator+(int y, const INT &x);
//显示数据
void display()const
{
    for (int i = 0; i <len; i++)
    cout << p_num[i];
    cout << endl;
}

};
INT operator+(const INT &x1, const INT &x2)
{
INT temp;
temp.p_num = new char[x1.len+x2.len+2];
if (x1.len>=x2.len)
{

    for (int i = temp.len-1; i >= 0; i--) { temp.p_num[i] = '0'; }
    for (int i = x2.len-1; i >= 0; i--)
    {
        temp.p_num[i] = temp.p_num[i] + x1.p_num[i] + x2.p_num[i] - '0';
        if (temp.p_num[i] - '0' > 10)
        {
            temp.p_num[i] -= 10; temp.p_num[i - 1] += 1;
        }
    }
    for (int i = temp.len-x2.len-1; i >= 0; i--)
    {
        temp.p_num[i] +=x1.p_num[i];
    }
}
else
{
    for (int i = temp.len-1; i >= 0; i--) { temp.p_num[i] = '0'; }
    for (int i = x1.len-1; i >= 0; i--)
    {
        temp.p_num[i] = temp.p_num[i] + x1.p_num[i] + x2.p_num[i] - '0';
        if (temp.p_num[i] - '0' > 10)
        {
            temp.p_num[i] -= 10; temp.p_num[i - 1] += 1;
        }
    }

    for (int i = temp.len-1; i >= 0; i--)
    {

        temp.p_num[i] += x2.p_num[i];
    }
   }
return temp;

}
int main()
{
INT x,y,z;
x = "123456789";
y = "12";
z=x+y;
z.display();
system("pause");
return 0;
}

  • 写回答

2条回答

  • threenewbee 2016-03-31 23:09
    关注

    错误太多了,比如说,你根本没有代码逻辑在加法中设置len,返回的INT的len是0,导致display根本不会循环。
    temp.p_num[i] = temp.p_num[i] + x1.p_num[i] + x2.p_num[i] - '0';
    这里每个数字都是ascii形式的,都需要减去'0',另外加法的进位也不对。

    参考下这个
    http://blog.csdn.net/hanangellove/article/details/42486723

    评论

报告相同问题?

悬赏问题

  • ¥50 有数据,怎么建立模型求影响全要素生产率的因素
  • ¥50 有数据,怎么用matlab求全要素生产率
  • ¥15 TI的insta-spin例程
  • ¥15 完成下列问题完成下列问题
  • ¥15 C#算法问题, 不知道怎么处理这个数据的转换
  • ¥15 YoloV5 第三方库的版本对照问题
  • ¥15 请完成下列相关问题!
  • ¥15 drone 推送镜像时候 purge: true 推送完毕后没有删除对应的镜像,手动拷贝到服务器执行结果正确在样才能让指令自动执行成功删除对应镜像,如何解决?
  • ¥15 求daily translation(DT)偏差订正方法的代码
  • ¥15 js调用html页面需要隐藏某个按钮