Exponentiation指数
Description
Problems involving涉及 the computation计算of exact values of very large magnitude级and precision are common. For example, the computation of the national debt is a taxing experience for many computer systems.
This problem requires that you write a program to compute the exact value of Rn where R is a real number ( 0.0 < R < 99.999 ) and n is an integer such that 0 < n <= 25.
Input
The input will consist of a set of pairs of values for R and n. The R value will occupy占据columns 1 through 6, and the n value will be in columns 8 and 9.
Output
The output will consist of one line for each line of input giving the exact value of R^n. Leading zeros should be suppressed in the output. Insignificant trailing zeros must not be printed. Don't print the decimal小数point if the result is an integer.
此题害我好惨,也反映了我思考问题的无序性
解题思路:
两个数高精度的乘法比较容易,求幂则可以反复的将一次的结果与之相乘。
此题比较难的是可能含有小数点,可以把此数看做整数最后再求小数点后移多少位即可。对于输出格式也要考虑全面如:.0000、10.123、10.000、.1234、100000这些小数点、零的问题。
2 #include<string.h>
3 #define Max 201
4 usingnamespace std;
5 int result[Max],result1[Max];
6 void Count(int n,int*result1,int*r,int len1)
7 {
8 int i,j,k,len2;
9 len2=len1;
10 for(k=1;k<n;++k)//第一次执行R^2,还要执行n-1次,所以k=1;k<n
11 {
12 for(i=0;i<len1;++i)//高精度乘法核心语句
13 for(j=0;j<len2;++j)
14 result[i+j]+=r[i]*result1[j];
15 for(i=0;i<len1+len2;++i)//进位计算
16 {
17 if(result[i]>9)
18 {
19 result[i+1]+=result[i]/10;
20 result[i]%=10;
21 }
22 }
23 i=Max-1;
24 while(result[i]==0)//找到当前result有效位数
25 --i;
26 len2=i+1;
27 for(j=0;j<len2;++j)
28 result1[j]=result[j];
29 memset(result,0,sizeof(result));//将result清0,所以下面调用Put函数时,用的数组时result1而不是result
30 }
31 }
32 void Put(int point)
33 {
34 int i,len2,z;
35 i=Max-1;
36 while(result1[i]==0&&i>=0)
37 --i;
38 len2=i;
39 if(len2==-1)//防止0.00000的情况
40 {
41 cout<<"0"<<endl;
42 return ;
43 }
44 if(point>len2+1)//防止.01234的情况
45 {
46 cout<<".";
47 for(i=0;i<point-len2-1;++i)
48 cout<<"0";
49 }
50 i=0;
51 while(result1[i]==0&&i<point)//找出需要省略0的个数z
52 ++i;
53 z=i;
54 for(i=len2;i>=z;--i)//省略0 i>=z
55 {
56
57 if(i==point-1)
58 cout<<".";
59 cout<<result1[i];
60 }
61 cout<<endl;
62 }
63 int main()
64 {
65 int i,j,point,n,len;
66 int r[6];
67 char R[7];
68 while(cin>>R>>n)
69 {
70 memset(result,0,sizeof(result));
71 memset(result1,0,sizeof(result));
72 point=0;
73 len=strlen(R);
74 for(i=5,j=0;i>=0;--i)
75 {
76 if(R[i]=='.')
77 {
78 point=5-i;
79 len-=1;//出现小数点则有效位数减一
80 }
81 else
82 {
83 r[j]=R[i]-'0';//由于有小数点的出现,使用变量j而不是i
84 result1[j]=R[i]-'0';
85 ++j;
86 }
87 }
88 Count(n,result1,r,len);//高精度计算
89 Put(point*n);//输出,计算后小数点位数为 point*n
90 }
91 return0;
92 }
8279126 |
Accepted |
264K |
16MS |
1402B |
2011-03-08 21:26:57 |