/*
題意:輸入一些大整數,輸出它們之和
在這道題中找到了一個重大的出錯原因,即②處的初始化
*/
#include <cstdio>
#include <cstring>
const int nMax = 200;
struct BigNumber
{
int data[nMax];
int len;
BigNumber(){len = 1; memset(data, 0, sizeof(data));}
BigNumber(char *str){*this = str;}
BigNumber & operator=(char *str);
BigNumber operator+(BigNumber &a);
void clearLeadZero();
void print();
};
BigNumber & BigNumber::operator=(char *str)
{
memset(data,0,sizeof(data));//①最新補充,如果你想將剩余部分都設置為零,則需要增加該語句!
len = strlen(str);
int i;
for(i = 0; i < len; ++ i)
data[i] = str[len - i - 1] - '0';
return *this;
}
BigNumber BigNumber::operator+(BigNumber &a)
{
int q = 0;
int i, j;
BigNumber z;
for(i = 0, j = 0;q || i < len || j < a.len; ++ i, ++ j)
{
int p = data[i] + a.data[j] + q;
z.data[i] = p % 10;
q = p / 10;
}
z.len = i;
z.clearLeadZero();
return z;
}
void BigNumber::clearLeadZero()
{
while(len > 1 && !data[len - 1]) -- len;
}
void BigNumber::print()
{
int i;
for(i = len -1; i >= 0; -- i)
printf("%d", data[i]);
printf("\n");
}
int main()
{
//freopen("f://data.in","r",stdin);
int T;
scanf("%d", &T);
BigNumber ans;
while(T--)
{
ans = "0";
char s[nMax];
while(scanf("%s", s) != EOF)
{
if(s[0] == '0' && s[1] == 0)
break;
ans = ans + BigNumber(s);
}
ans.print();
if(T)
printf("\n");
}
return 0;
}
摘自 lhshaoren