A+B Problem IV
时间限制:1000 ms | 内存限制:65535 KB
难度:3
- 描述
- acmj最近发现在使用计算器计算高精度的大数加法时很不方便,于是他想着能不能写个程序把这个问题给解决了。
- 输入
- 包含多组测试数据
每组数据包含两个正数A,B(可能为小数且位数不大于400) - 输出
- 每组输出数据占一行,输出A+B的结果,结果需要是最简的形式。
- 样例输入
-
1.9 0.1 0.1 0.9 1.23 2.1 3 4.0
- 样例输出
-
2 1 3.33 7
字符串处理
考虑0这个特殊的数#include <stdio.h> #include <string.h> #define N 905 char ch_1[N],ch_2[N],ch1_1[N],ch1_2[N]; char ch3[N],ch4[N]; char ch5[N],ch6[N];/*整数加 和小数后的加*/ void f() { ch_1[0] = '\0'; ch_2[0] = '\0'; ch1_1[0] = '\0'; ch1_2[0] = '\0'; ch5[0] = '\0'; ch6[0] = '\0'; } void judge_char(char ch[],char ch1[],char ch2[]) { ch1[0] = '\0'; ch2[0] = '\0'; int i = 0; for(i = 0; i < strlen(ch); i++) if(ch[i] == '.') break; int j = 0,k = 0; for(j = 0; j < i; j++) ch1[j] = ch[j]; ch1[j++] = '\0'; int t = 0; for(k = i+1; k < strlen(ch); k++) { ch2[t++] = ch[k]; } ch2[t] = '\0'; } void add_int(char ch[],char ch1[],char ch2[],int kk)/*ch为长度短着 整数相加*/ { ch2[0] = '\0'; int i = 0,j = 0; int k = strlen(ch1)-1; int t = kk; int t1 = 0; int x = 0; for(i = strlen(ch)-1; i >= 0; i--) { x = (int) ch[i] + (int)ch1[k] - 2*'0' + t; t = x /10; x = x % 10; ch2[t1++] = x + '0'; k--; } for(j = k; j >= 0; j--) { x = (int)ch1[j] +t - '0'; t = x /10; x = x % 10; ch2[t1++] = x + '0'; } if(t) { ch2[t1++] =(char)(t + '0'); t = 0; } ch2[t1++] = '\0'; } int add_float(char ch[],char ch1[],char ch2[])/*小数相加 ch为长度短着*/ { ch2[0] = '\0'; int i = 0; int j = 0; int k = 0; int t = 0; int t1 = 0; int x = 0; for(i = strlen(ch1) - 1; i >= strlen(ch); i--) { x = (int)(ch1[i] + t - '0'); t = x/10; x %= 10; ch2[t1++] =(char)(x + '0'); } for(j = strlen(ch)-1; j >=0 ; j--) { x = (int)(ch[j] + ch1[j] + t - 2*'0'); t = x /10; x = x % 10; ch2[t1++] = (char)(x + '0'); } ch2[t1++] = '\0'; return t; } int main() { while(scanf("%s%s",ch3,ch4) !=EOF) { f(); int kk = 0; judge_char(ch3,ch_1,ch_2); judge_char(ch4,ch1_1,ch1_2); if(ch_2[0] == '\0') { ch_2[0] = '0'; ch_2[1] = '\0'; } if(ch1_2[0] == '\0') { ch1_2[0] = '0'; ch1_2[1] = '\0'; } if(strlen(ch_2) > strlen(ch1_2)) kk = add_float(ch1_2,ch_2,ch6); else kk = add_float(ch_2,ch1_2,ch6); if(strlen(ch_1) > strlen(ch1_1) ) add_int(ch1_1,ch_1,ch5,kk); else add_int(ch_1,ch1_1,ch5,kk); int i = 0; int xx = 0; int yy = 0; for(i = 0;i <= strlen(ch6)-1; i++) if(ch6[i] == '0') xx++; if(xx == strlen(ch6) ) { yy = strlen(ch5)-1; for(i = yy; i >= 0; i-- ) if(ch5[i] != '0') break; while(yy >= 0) { printf("%c",ch5[yy]); yy--; } printf("\n"); } else { yy = strlen(ch5)-1; while(yy >= 0) { printf("%c",ch5[yy]); yy--; } printf("."); yy = strlen(ch6)-1; i = 0; while(i <= yy) { if(ch6[i] != '0') break; i++; } while(yy >= i) { printf("%c",ch6[yy]); yy--; } printf("\n"); } } return 0; }