标签:
> 总体思路:
1 #include "stdio.h" 2 #include "string.h" 3 4 int main(void) 5 { 6 char s[8] = {0} ; 7 int sLen = 0 ; 8 int n = 0 ; 9 int decimalCnt = 0 ; 10 int base[8] = {0} ; 11 int baseCnt = 0 ; 12 int result[128] = {0} ; 13 int resultCnt = 0 ; 14 int tmp[128] = {0} ; 15 int tmpCnt = 0 ; 16 int i = 0, j = 0, k = 0 ; 17 18 while(scanf("%s%d", s, &n) != EOF) 19 { 20 /* TODO: 正式使用时添加输入检测 */ 21 22 if(0 == n) 23 { 24 printf("1\r\n") ; 25 continue ; 26 } 27 28 /* 计算字符串的长度 29 * 计算小数位数 30 * 去除高位无效的0 */ 31 tmpCnt = 0 ; 32 decimalCnt = 0 ; 33 for(i = 0; i < sizeof(s); i++) 34 { 35 if(0 == s[i]) 36 { 37 sLen = i; 38 break ; 39 } 40 if(‘.‘ == s[i]) 41 { 42 decimalCnt = sizeof(s) - i - 1 ; 43 continue ; 44 } 45 if(‘0‘ == s[i] && 0 == tmpCnt) 46 continue ; 47 48 tmp[tmpCnt++] = s[i] - ‘0‘ ; 49 } 50 if(decimalCnt) 51 decimalCnt -= sizeof(s) - sLen; 52 53 /* 存在小数位,去除末尾无效的0*/ 54 if(decimalCnt && tmpCnt) 55 { 56 for(i = sLen - 1; i >= 0; i--) 57 { 58 if(s[i] != ‘0‘) 59 break ; 60 61 decimalCnt-- ; 62 tmpCnt-- ; 63 } 64 } 65 if(0 == tmpCnt) 66 { 67 printf("0\r\n") ; 68 continue ; 69 } 70 71 /* 数组第0位对应最低位 */ 72 resultCnt = 0 ; 73 baseCnt = 0 ; 74 for(i = tmpCnt - 1; i >= 0; i--) 75 { 76 result[resultCnt++] = tmp[i] ; 77 base[baseCnt++] = tmp[i] ; 78 } 79 80 /* 竖式乘法 */ 81 for(i = 1; i < n; i++) 82 { 83 memset(tmp, 0, sizeof(tmp)) ; 84 for(j = 0; j < resultCnt; j++) 85 for(k = 0; k < baseCnt; k++) 86 { 87 tmp[j+k] += result[j] * base[k] ; 88 } 89 90 tmpCnt = resultCnt + baseCnt - 1; 91 for(j = 0; j < tmpCnt; j++) 92 { 93 tmp[j+1] += tmp[j] / 10 ; 94 tmp[j] = tmp[j] % 10 ; 95 } 96 if(tmp[j]) 97 tmpCnt += 1 ; 98 99 for(j = 0; j < tmpCnt; j++) 100 result[j] = tmp[j] ; 101 resultCnt = tmpCnt ; 102 } 103 104 /* 输出结果,注意小数位数大于结果位数的情况 */ 105 decimalCnt *= n ; 106 for(i = decimalCnt - 1; i >= resultCnt; i--) 107 { 108 if(i+1 == decimalCnt) 109 printf(".") ; 110 printf("0") ; 111 } 112 for(i = resultCnt - 1; i >= 0; i--) 113 { 114 if(i+1 == decimalCnt) 115 printf(".") ; 116 117 printf("%d", result[i]) ; 118 } 119 printf("\r\n") ; 120 } 121 }
> 附测试数据
95.123 12
0.4321 20
5.1234 15
6.7592 9
98.999 10
1.0100 12
.00001 1
.12345 1
0001.1 1
1.1000 1
10.000 1
000.10 1
000000 1
000.00 1
.00000 0
000010 1
000.10 1
0000.1 1
00.111 1
0.0001 1
0.0001 3
0.0010 1
0.0010 3
0.0100 1
0.0100 3
0.1000 1
0.1000 3
1.0000 1
1.0000 3
1.0001 1
1.0001 3
1.0010 1
1.0010 3
1.0100 1
1.0100 3
1.1000 1
1.1000 3
10.000 1
10.000 3
10.001 1
10.001 3
10.010 1
10.010 3
10.100 1
10.100 3
99.000 1
99.000 3
99.001 1
99.001 3
99.010 1
99.010 3
99.100 1
99.100 3
99.998 1
99.998 3
标签:
原文地址:http://www.cnblogs.com/codesworld/p/4681479.html