【HDOJ】1753 大明A+B

时间:2021-06-05 15:02:23

注意数据格式,可以是整数,并且注意输出最简化浮点数。

 #include <stdio.h>
#include <string.h> #define MAXNUM 420 char a[MAXNUM], b[MAXNUM], c[MAXNUM], d[MAXNUM];
int lena, lenb;
int posa, posb; int addf(int bega, int begb, int *carry);
int addi(int enda, int endb, int carry);
void add();
void output(int in, int fn); int main() { while (scanf("%s %s", a, b) != EOF) {
add();
memset(a, , sizeof(a));
memset(b, , sizeof(b));
memset(c, , sizeof(c));
memset(d, , sizeof(d));
} return ;
} void add() {
int i, carry, in, fn; posa = posb = -;
for (i=; i<MAXNUM; ++i) {
if (a[i] == '\0')
break;
else if (a[i] == '.')
posa = i;
else
a[i] -= '';
}
lena = i;
if (posa == -)
posa = lena; for (i=; i<MAXNUM; ++i) {
if (b[i] == '\0')
break;
else if (b[i] == '.')
posb = i;
else
b[i] -= '';
}
lenb = i;
if (posb == -)
posb = lenb; fn = addf(posa+, posb+, &carry);
in = addi(posa, posb, carry);
output(in, fn);
} void output(int in, int fn) {
int i; // printf the integer part
while (in>= && c[in]==)
--in;
if (in < )
printf("");
else {
for (i=in; i>=; --i)
printf("%d", c[i]);
} fflush(stdout);
// printf the float part
while (fn>= && d[fn]==)
--fn;
if (fn>=) {
printf(".");
for (i=; i<=fn; ++i)
printf("%d", d[i]);
}
printf("\n");
fflush(stdout);
} int addi(int enda, int endb, int carry) {
int cn = ; while (enda || endb) {
c[cn] += carry;
if (enda) {
--enda;
c[cn] += a[enda];
}
if (endb) {
--endb;
c[cn] += b[endb];
}
carry = c[cn]/;
c[cn] %= ;
++cn;
}
c[cn] += carry; return cn;
} int addf(int bega, int begb, int *carry) {
int i, len, ov = ;
int flena = lena - bega;
int flenb = lenb - begb; len = (flena>flenb) ? flena : flenb; for (i=len-; i>=; --i) {
d[i] += ov;
if (bega+i < lena)
d[i] += a[bega+i];
if (begb+i < lenb)
d[i] += b[begb+i];
ov = d[i]/;
d[i] %= ;
} *carry = ov; return len;
}