POJ 1001 Exponentiation

高精度计算,用一个类来实现,提交时N次表达错误,改了N次才成功。。。。

 

#include<iostream>
#include<string>
using namespace std;
#define MAX 126

class Num{
public:
 int nums[MAX];
 int length;
 int dec;
 Num(string s);
 void mul(Num m);
 void format();
};

Num::Num(string s)
{
 
 int t1=0,t2=0,pos=0,n1=0,n2=0;;
 while(t1<6&&(s[t1]=='0'||s[t1]=='.'))
 {
  if(s[t1]=='0')
   n1++;
  t1++;
 }
 while(s[pos]!='.'&&pos<6)
  pos++;
 t2=5;
 while(t2>0&&(s[t2]=='0'||s[t2]=='.'))
 {
  if(s[t2]=='0')
   n2++;
  t2--;
 }
 length=5-n1-n2;
 int t=0;
 for(int i=t1;i<=t2;i++)
 {
  if(s[i]!='.')
  {
   nums[t]=s[i]-'0';
   t++;
  }
 }
 dec=5-pos-n2;
 if(t1>t2)
 {
  length=0;
  dec=0;
 }

}

void Num::mul(Num m)
{
 int oldLength=length;
 length+=m.length;
 dec+=m.dec;
 int *res=new int[length]();
 memset(res,0,length);
 for(int i=0;i<m.length;i++)
 {
  for(int j=0;j<oldLength;j++)
  {
   res[i+j]+=nums[oldLength-j-1]*m.nums[m.length-i-1];
  }
 }
 for(int i=0;i<length-1;i++)
 {
  res[i+1]+=res[i]/10;
  res[i]%=10;
 }
 int t1=0;
 while(res[t1]==0)
  t1++;
 dec-=t1;
 int t2=0;
 while(res[length-1-t2]==0)
  t2++;
 int temp=length-t2-t1;
 for(int i=0;i<temp;i++)
 {
  nums[i]=res[length-t2-1-i];
 }
 length=temp;
 
};

int main()
{
 string s;
 int n;
 while(cin>>s>>n)
 {
  Num num(s);
  Num t(s);
  if(num.length==0)
  {
   cout<<"."<<endl;
   continue;
  }
  for(int i=0;i<n-1;i++)
  {
   num.mul(t);
  }
  if(num.dec>0)
  {
   if(num.length>num.dec)
   {
    int i;
    for(i=0;i<num.length-num.dec;i++)
    {
     cout<<num.nums[i];
    }
    cout<<".";
    for(;i<num.length;i++)
    {
     cout<<num.nums[i];
    }
    cout<<endl;
   }
   else if(num.length==num.dec)
   {
    cout<<".";
    for(int i=0;i<num.length;i++)
    {
     cout<<num.nums[i];
    }
    cout<<endl;
   }
   else
   {
    int n=num.dec-num.length;
    cout<<".";
    for(int i=0;i<n;i++)
    {
     cout<<"0";
    }
    for(int i=0;i<num.length;i++)
    {
     cout<<num.nums[i];
    }
    cout<<endl;
   }
   
  }
  else
  {
   int n=0-num.dec;
   for(int i=0;i<num.length;i++)
   {
    cout<<num.nums[i];
   }
   for(int i=0;i<n;i++)
   {
    cout<<"0";
   }
   cout<<endl;
  }
 }
 return 0;
}

 

 

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值