#include <stdio.h> #include <string.h> #include <stdlib.h> #include <math.h> #ifdef WIN32 typedef __int64 int64; #else typedef long long int64; #endif typedef struct _bignum { int64 data[0x20]; /* 默认分0x20段,每段5位 */ int segsize; /* 实际段数 */ int np; /* 小数位数 */ } Bignum; typedef struct _intnum { int64 data; int np; } Intnum; void printBignum(Bignum *num); void getInput(Intnum *num, int *exp) { char str[0x10]; num->np = 0; if (scanf("%s%d", str, exp) == 2) { char c; int i = 0; /* calulate the little number...-__-|| */ while((c = str[i++]) != '\0') { if (c == '.') { num->np = 6 - i; break; } } num->data = (int)(atof(str) * pow(10, num->np)); } } void mul(Bignum a, Intnum b, Bignum *result) { int i; int64 overflow = 0; result->np = a.np + b.np; for (i=0;i<a.segsize;++i) { int64 inter = a.data[i] * b.data + overflow; overflow = inter / 100000; result->data[i] = inter % 100000; } while (overflow > 0) { result->data[i++] = overflow % 100000; overflow /= 100000; } result->segsize = i; } void power(Intnum base, int exp, Bignum *result) { int i; result->data[0] = 1; result->np = 0; result->segsize = 1; if (exp == 0) { result->data[0] = 0; result->np = 0; return; } for (i=0; i<exp; ++i) { mul(*result, base, result); } } void printBignum(Bignum *num) { int i; int pointSeg; int pointOff = num->np % 5; char buffer[0x100] = {0}; char *buffer_p = buffer; int offset = 0; if (num->np <= 0) { pointSeg = -1; } else { pointSeg = num->np / 5; } for (i=num->segsize; i<=pointSeg; ++i) { num->data[i] = 0; num->segsize++; } for (i=num->segsize-1; i>=0 ; i--) { if (i == pointSeg) { char buf[0x10] = {0}; int j; sprintf(buf, "%05ld", num->data[i]); for (j=0; j<pointOff; j++) { buf[5-j] = buf[4-j]; } buf[5-j] = '.'; buf[6] = '\0'; offset += sprintf(buffer + offset, "%s", buf); } else { offset += sprintf(buffer + offset, "%05ld", num->data[i]); } } i = 0; while('0' == buffer[i++]) { ; } buffer_p = buffer + i - 1; if (num->np > 0) { i = strlen(buffer) - 1; while('0' == buffer[i--]) { ; } if (buffer[i+1] == '.') { buffer[i+1] = '\0'; } else { buffer[i+2] = '\0'; } } printf("%s\n", buffer_p); } int main() { int exp; Intnum source = {0}; Bignum result = {0}; getInput(&source, &exp); power(source, exp, &result); printBignum(&result); return 0; }
Wrong Answer, why?????