标签:har input ons sum des tom nes out content
//高精度加法,注意格式 #define _CRT_SECURE_NO_WARNINGS #include<stdio.h> #include<stdlib.h> #include<string.h> #include<memory.h> #define SIZE 1005 int main() { int i, n; int j, k, m; int index; int lengthA, lengthB; char a[SIZE]; char b[SIZE]; int ans[SIZE]; int carryBit; //进位 //freopen("F:\\input.txt","r",stdin); scanf("%d", &n); for(i = 0; i < n; i++) { scanf("%s%s", a, b); memset(ans, 0, sizeof(ans)); index = 0; carryBit = 0; lengthA = strlen(a); lengthB = strlen(b); lengthA--; lengthB--; while ((lengthA >= 0) && (lengthB >= 0)) { //将char转换为int,并计算和,如果ans大于10,则carryBit为1,否则为0 ans[index] = (a[lengthA] - ‘0‘) + (b[lengthB] - ‘0‘) + carryBit; if (ans[index] >= 10) { carryBit = ans[index] / 10; ans[index] %= 10; } else carryBit = 0; index++; lengthA--; lengthB--; } //如果A的长度大于B,则将A与carryBit相加 while (lengthA >= 0) { ans[index] = (a[lengthA] - ‘0‘) + carryBit; if (ans[index] >= 10) { carryBit = ans[index] / 10; ans[index] %= 10; } else carryBit = 0; index++; lengthA--; } //如果B的长度大于A,则将B与carryBit相加 while (lengthB >= 0) { ans[index] = (b[lengthB] - ‘0‘) + carryBit; if (ans[index] >= 10) { carryBit = ans[index] / 10; ans[index] %= 10; } else carryBit = 0; index++; lengthB--; } if (carryBit != 0) { ans[index]++; index++; } //去掉多余的零 while (ans[index] == 0) index--; printf("Case %d:\n", i + 1); printf("%s + %s = ", a, b); //两个零字符串相加输出为0 if (index == -1) printf("0"); else { for (m = index; m >= 0; m--) printf("%d", ans[m]); } printf("\n"); if (i != n - 1) printf("\n"); } //freopen("con", "r", stdin); //system("pause"); return 0; }
标签:har input ons sum des tom nes out content
原文地址:https://www.cnblogs.com/mycodinglife/p/10507568.html