当要执行相加的两个数超出C语言所能表示的范围时,就不能用正常的加法运算来执行相加操作,这时候可以用两个字符数组接收要相加的两个大数,
然后从两个大数的地位进行按位相加,并设置一个进位标志,如果标志为1,表示有进位,否则没有进位。
要注意的是字符数组的地位为数字的高位,所以要从数组下标大的地方开始相加。
#include <stdio.h>
#include <string.h>
int main(){
char a[100],b[100]; //a,b数组接收两个数,c为结果数组
char c[101];
int alen,blen;
int carry = 0;
int i,j,k;
int temp;
printf("enter a number: "); //输入数字,低下标是数的高位
gets(a);
printf("enter another number: ");
gets(b);
alen = strlen(a);
blen = strlen(b);
k = 0;
//从数组高位开始相加,直到有一个数组已经加完
for(i=alen-1,j=blen-1;i>=0 && j>=0;i--,j--){
temp = a[i]-'0'+b[j]-'0'+carry; //将字符转换为数字相加,结果为数字
if(temp>=10){
temp -= 10;
carry = 1;
}else{
carry = 0;
}
c[k] = temp+'0'; //将结果转换为字符存储
k++;
}
//下面两个循环用于将未加完的数组加到结果数组中
while(i>=0){
temp = a[i]-'0'+carry;
if(temp>=10){
temp -= 10;
carry = 1;
}else{
carry = 0;
}
c[k] = temp+'0';
i--;
k++;
}
while(j>=0){
temp = b[j]-'0'+carry;
if(temp>=10){
temp -= 10;
carry = 1;
}else{
carry = 0;
}
c[k] = temp+'0';
j--;
k++;
}
if(carry){ //如果最后还有进位,则将最高位置为1,k此时并不增加,k表示结果的最高位
c[k] = 1+'0';
}else{ //否则将k的值减一
k--;
}
while(k>=0){ //从最高位开始输出
printf("%c",c[k--]);
}
printf("\n");
return 0;
}