在字符串里存入输入的大数,然后转存到整形数组temp中,一位一位相加,判断是否进位,因为数字的高低位和数组的高低位不同,所以temp中数字顺序要反过来,然后输出result时,倒序输出就是结果。
#include <iostream>
#include <string>
#include <cstdio>
#include <cstring>
using namespace std;
int main()
{
char a[101] = { '\0' };
int temp[110], result[110];
for (int i = 0; i < 110; i++)
{
temp[i] = 0;
result[i] = 0;
}
while (cin >> a)
{
int size_a = strlen(a);
if (size_a == 1 && a[0] == '0')
break;
for (int i = 0; i < size_a; i++)
{
temp[i] = a[size_a - i - 1] - '0';
}
for (int j = 0; j < 110; j++)
{
result[j] += temp[j];
if (result[j] >= 10)
{
result[j] -= 10;
result[j + 1] += 1;
}
}
}
int flag = 1;
int index = 0;
for (int i = 109; i != 0 && flag == 1; i--)
{
if (result[i] != 0)
{
index = i;
flag = 0;
}
}
for (int i = index; i >= 0; i--)
{
cout << result[i];
}
cout << endl;
system("pause");
return 0;
}
运行结果为: