//思路:1.調(diào)用函數(shù)change() 將小數(shù) s 轉(zhuǎn)化成去掉小數(shù)點(diǎn)的整數(shù) s1 并且返回得到小數(shù)點(diǎn)的位置。
// 2.調(diào)用函數(shù)mu1()用大數(shù)乘法模擬整數(shù)運(yùn)算,并將相乘的結(jié)果放在s2中,返回s2和是進(jìn)行下面的 n -1次相乘
// 3.在主函數(shù)里面通過已知的小數(shù)點(diǎn)的位置,利用數(shù)值關(guān)系輸出
// 4.注意小數(shù)點(diǎn)前沒有前導(dǎo)0,小數(shù)點(diǎn)后面沒有尾0。
//難點(diǎn):for ( int i = 1; i < n; i ++) mu1 (s1,s2);
1
2
#include <stdio.h>
3
#include <stdlib.h>
4
#include <string.h>
5
#define LENGTH 6 //小數(shù)的位數(shù)(含小數(shù)點(diǎn))
6
7
//將字符轉(zhuǎn)化為數(shù)字
8
unsigned int change (char s[LENGTH], unsigned int s1[LENGTH - 1])
9

{
10
int ss[LENGTH - 1]; //ss 放未逆置的整數(shù)
11
memset (ss, 0, sizeof(ss));
12
13
int k = 0 ;
14
for (int i = 0; i < LENGTH && s[i]; ++i) //考慮特殊數(shù)據(jù)如:0.0001
15
{
16
if (s[i] != '.')
17
ss[k++] = s[i] - '0';
18
}
19
for (int j = 0;j < LENGTH - 1; j++)
20
{
21
s1[j] = ss[LENGTH - 2 - j];
22
}
23
24
int m = 0;
25
while ( (s[m] != '.') && s[m] )
26
++m;
27
return LENGTH - 1 - m; //小數(shù)點(diǎn)位數(shù)
28
}
29
30
//大數(shù)乘法運(yùn)算
31
//函數(shù)返回 s2
32
void mu1 (unsigned int s1[LENGTH - 1],unsigned int s2[130])
33


{
34

int ss[130];
35

memset ( ss, 0, sizeof(ss) );
36
37
for ( int i = 0; i < LENGTH - 1; i++)
38
for (int j = 0;j < 130; j++) //難點(diǎn):因?yàn)榉祷匦碌膕2之后位數(shù)會(huì)增加 最多時(shí) 5* 25 = 125
39
ss [i + j] += s1[i] * s2[j];
40
41

//將 兩個(gè)大數(shù)相乘得的積ss中進(jìn)行進(jìn)位處理后放到s2 中
42

int c = 0;
43

for (int i = 0;i < 130;i++)
44


{
45

s2[i] = (c + ss[i]) % 10;
46

c = (c + ss[i]) / 10;
47

}
48

}
49
50
int main()
51

{
52
int n;
53
char s[LENGTH]; //要處理的冪 R
54
unsigned int s1[LENGTH - 1]; //將 R 轉(zhuǎn)化成數(shù)字
55
unsigned int s2[130];
56
57
while(scanf ("%s%d", s, &n) != EOF)
58
{
59
memset (s1, 0, sizeof (s1));
60
memset (s2, 0, sizeof (s2));
61
62
int j = change (s, s1); //得到小數(shù)點(diǎn)所在位置
63
change (s,s2); //得到s2 和 s1 進(jìn)行冪運(yùn)算
64
for ( int i = 1; i < n; i ++)
65
mu1 (s1,s2);
66
67
//在s2中前面的代表小數(shù)位,后面的代表整數(shù)位,
68
//所以關(guān)鍵是通過數(shù)值關(guān)系找到小數(shù)點(diǎn)的位置
69
70
71
//例:0.1010 * 0.1010 = 0.01020100
72
int m = 129;//去掉前導(dǎo)0
73
while ( (!s2[m]) && m)
74
--m;
75
76
int k = 0; //去掉尾0
77
while ( ( !s2[k] ) && (k < 130))
78
++k;
79
80
//輸出整數(shù)位
81
for (int i = m; i >= n * j; i--)
82
printf ("%d",s2[i]);
83
84
//輸出小數(shù)點(diǎn)
85
if ( j && n * j >= k + 1)
86
printf (".");
87
88
for (int i = n*j -1; i >= k; --i)
89
printf ("%d", s2[i]);
90
printf ("\n");
91
}
92
93
return 0;
94
// system ("pause");
95
}
96
posted on 2010-08-09 13:21
雪黛依夢(mèng) 閱讀(624)
評(píng)論(0) 編輯 收藏 引用 所屬分類:
大數(shù)