最简单的模拟题,没什么好说的,模拟加法运算,但是细节很重要。
对于比较边缘的数据,如:99+1 99+111要着重关注
#include <stdio.h> #include <string.h> #include <stdlib.h> char num1[1010], num2[1010]; int size1 = sizeof(num1), size2 = sizeof(num2); char c_num1[1010], c_num2[1010]; int main() { #if 0 freopen("data.in", "r", stdin); freopen("data.out", "w", stdout); #endif // 1 int T, cou = 0, len1, len2, s_len, b_len, i, t, tt, first = 1; char *big, *small; while (~scanf("%d", &T)) { while (T--) { memset(num1, 0, size1); ///对两个字符串初始化,全部赋值0,方便两字符串数组直接相加 memset(num2, 0, size2); scanf("%s %s", num1, num2); strcpy(c_num1, num1); ///备份数组,最后输出时用 strcpy(c_num2, num2); len1 = strlen(num1); len2 = strlen(num2); if (len1 > len2) { ///找出较长的数组,作为相加的根基 big = num1; small = num2; b_len = len1; s_len = len2; } else { big = num2; small = num1; b_len = len2; s_len = len1; } strcpy(big, strrev(big)); ///利用库函数进行字符数组倒置,再拷贝回原数组,原因是加法竖式运算的时候是右对齐,而字符数组是左对齐 strcpy(small, strrev(small)); tt = 0; ///用于存储进一 for (i = 0; i < b_len; i++) { ///直接以长的字符数组的长度为准直接相加,因为对数组初始化了,除了输入的字符,其他全为0即'\0',注意不是'0' if (i < s_len) t = big[i] - '0' + small[i] - '0' + tt; ///数字字符到数字的转换,注意此时两个都是数字字符 else t = big[i] - '0' + small[i] + tt; ///数字字符到数字的转化,注意此时big[i]是数字字符,而small[i]为0即'\0' if (t >= 10) { big[i] = t % 10 + '0'; tt = 1; } else { big[i] = t + '0'; tt = 0; ///不要忘记在没有进位时重新赋值0 } } if (tt) { big[i] = '1'; ///对于最后一位是否进一的判断赋值 } strcpy(big, strrev(big)); if (!first) puts(""); ///空行 if (first) first = 0; printf("Case %d:\n", ++cou); printf("%s + %s = ", c_num1, c_num2); if (tt) { puts(big); } else { puts(big); } } } return 0; }