问题描述:重点在于两个大数相加,第一行输入要计算的case数,接下来每行输入两个数字,用空格隔开。输出sum,并且两个case之间用两行空白行隔开。
Sample Input
2 1 2 112233445566778899 998877665544332211
Sample Output
Case 1: 1 + 2 = 3 Case 2: 112233445566778899 + 998877665544332211 = 1111111111111111110
#include<stdio.h>
#include<string.h>
int main(){
int T;
int i,j,count=0;
int num1len,num2len,numsumlen,numsumlen1;
unsigned char c,flag=0;
char num1[20][1000],num2[20][1000],numsum[20][1000];
scanf("%d",&T);//输入要计算的case数
for(i=0;i<T;i++){
scanf("%s%s",&num1[i],&num2[i]);//字符串输入
}
for(i=0;i<T;i++){
num1len = strlen(num1[i]) - 1;
num2len = strlen(num2[i]) - 1;
numsumlen = (num1len>num2len? num1len : num2len) + 2;//比最长的数组还要多长2,一个用来在后面装'\0',一个用来装可能的进位
numsumlen1 = numsumlen;//后面还要用到一次,而原来的numsumlen变动了
numsum[i][numsumlen--] = '\0';
count = 0;
for(;num1len>=0&&num2len>=0;){
c = num1[i][num1len--] + num2[i][num2len--] -'0' + flag;//获取每位的字符,从后面开始取
if(c>'9'){
flag = 1;
numsum[i][numsumlen--] = c - 10;
}
else{
flag = 0;
numsum[i][numsumlen--] = c;
}
}
if(num1len<0)
while(num2len>=0){
c = num2[i][num2len--] + flag;
if(c>'9'){
flag = 1;
numsum[i][numsumlen--] = c - 10;
}
else{
flag = 0;
numsum[i][numsumlen--] = c;
}
}
else
while(num1len>=0){
c = num1[i][num1len--] + flag;
if(c>'9'){
flag = 1;
numsum[i][numsumlen--] = c - 10;
}
else{
flag = 0;
numsum[i][numsumlen--] = c;
}
}
if(flag)
numsum[i][0] = '1';
else{
numsum[i][0] = '0';
}
j=0;
while(numsum[i][j++] == '0')
count++;
for(j=0;j<numsumlen1;j++)
numsum[i][j] = numsum[i][j+count];//去除数组在前面的0
printf("Case %d:\n%s + %s = %s", i+1, num1[i], num2[i], numsum[i]);
if(i != T-1)
printf("\n\n");
else
printf("\n");
}
}