主要思路:
由于大数不可存入int
数组中,所以将数字转为字符输入char
数组中,将两个数组数字从个位开始,模拟正常数字加法,需要进位1时设置进位标志,两数相加大于10时进位,见具体代码。
#include <string.h>
#include <stdio.h>
int main ()
{
char a[100], b[100], c[101]; //创建用于接收两个大数的字符数组以及接收相加后结果的数组,两个100位的大数相加,最多101位
int i, j, count = 0, alen, blen, carry = 0, temp;
//i,j为循环标志, count为接收结果的数组的长度, temp为数字每一位相加之后的结果, carry为进位标志,若为进位即为1否则为0
gets(a);
gets(b);
alen = strlen(a);
blen = strlen(b);
for (i = alen-1, j = blen-1; i>=0 && j>=0; i--,j--) //将两个数字从个位逐加,即从数组的最高位加起
{
temp = a[i] - '0' + b[j] - '0' + carry; //模拟每一位相加的过程,将字符转换为数字字符,carry为进位标志
if (temp >= 10){
temp = temp - 10;
carry = 1; //每一位相加后大于10即表示有进位
}else{
carry = 0;
}
c[count++] = temp + '0'; //相加后的结果暂时转为字符进行处理
}
//当逐位相加,某个数组有剩余时
while (i >= 0){
temp = a[i] - '0' + carry; //此时仍需要加carry的原因是有可能在最后一位相加后需要进位
if (temp >= 10){
temp = temp - 10;
carry = 1;
}else {
carry = 0;
}
c[count++] = temp + '0';
i--;
}
while (j >= 0){
temp = b[j] - '0' + carry;
if (temp >= 10){
temp = temp - 10;
carry = 1;
}else {
carry = 0;
}
c[count++] = temp + '0';
j--;
}
if (carry){ //若最后还有进位,则使最高位为1
c[count] = 1 + '0';
}else {
count--; //由于前一步是count++,count已经自加,由于没有进位,则使count--
}
while (count >= 0){
printf ("%c",c[count--]);
}
return 0;
}