Poj 1001

第一次做高精度的题。

做这道题的时候中间经历了一次期末考,前前后后改了小半个月。

最开始的参考找不到了。

刚写出来的时候因为WA看了Discuss里的测试用例,改了很多的小细节。但是还是一直WA。

放假后重拾这道题,参考了http://blog.csdn.net/alongela/article/details/6788237,改了输入不完善的地方。

又找了很多的测试用例,最后在http://blog.csdn.net/keysona/article/details/46371871的测试用例中发现是自己数组开的太小了……Orz

  1 #include<iostream>
  2 #include<cstring>
  3 using namespace std;
  4 
  5 struct floatint{
  6     int digits[999];
  7     int len;
  8     int pos;
  9 };
 10 
 11 floatint input(string s){
 12     floatint f;
 13     memset(f.digits,0,sizeof(f.digits));
 14     f.pos=0; 
 15     int l=0;
 16     for(int i=s.length()-1;i>-1;i--){
 17         if(s[i]=='.'){
 18             f.pos=l;
 19         }
 20         if(s[i]!='.'){
 21             f.digits[l]=s[i]-48;
 22             l++;
 23         }
 24     }
 25     f.len=l+1;
 26     return f;
 27 }
 28 
 29 void print(floatint a){
 30     int begin=a.len-1,end=0;
 31     for(int i=0;i<a.len-a.pos;i++){
 32         if(a.digits[begin]==0){
 33             begin--;
 34         }
 35         else{
 36             break;
 37         }
 38     }
 39     for(int i=0;i<a.pos;i++){
 40         if(a.digits[end]==0){
 41             end++;
 42         }
 43         else{
 44             break;
 45         }
 46     }
 47     if(begin<end){
 48         cout<<0;
 49         return;
 50     }
 51     for(int i=begin;i>end-1;i--){
 52         if(i==a.pos-1){
 53             cout<<'.';
 54         }
 55         cout<<a.digits[i];
 56     }
 57 }
 58 
 59 floatint multiply(floatint a,floatint b){
 60     floatint c;
 61     memset(c.digits,0,sizeof(c.digits));
 62     c.len=a.len+b.len;
 63     c.pos=a.pos+b.pos;
 64     for(int i=0;i<a.len;i++){
 65         for(int j=0;j<b.len;j++){
 66             c.digits[i+j]+=a.digits[i]*b.digits[j];
 67         }
 68     }
 69     for(int i=0;i<c.len;i++){
 70         if(c.digits[i]>9){
 71             c.digits[i+1]+=c.digits[i]/10;
 72             c.digits[i]=c.digits[i]%10;
 73         }
 74     }
 75     return c;
 76 }
 77 
 78 floatint d_multiply(floatint a,int n){
 79     if(n==0){
 80         floatint x;
 81         x.len=1;
 82         x.pos=0;
 83         memset(x.digits,0,sizeof(x.digits));
 84         x.digits[0]=1;
 85         return x;
 86     }
 87     if(n==1){
 88         return a;
 89     }
 90     else{
 91         return multiply(a,d_multiply(a,n-1));
 92     }
 93 }
 94 
 95 int main(){
 96     floatint r;
 97     char s[6];
 98     int n;
 99     while(cin>>s>>n){
100         r=input(s);
101         print(d_multiply(r,n));
102         cout<<endl;
103     }
104     return 0;
105 } 

注意memset的用法,另外将函数的实现从主函数中分离出来可以让代码的整洁性更好,也更便于修改。

posted @ 2017-01-20 19:06  水野玛琳  阅读(201)  评论(0编辑  收藏  举报