本来以前也写过,但是由于许多细节问题,没有AC,今天修改了一下,终于AC了,以前没有AC的具体原因总结了了一下,必须任何数的0次方都等于1没有考虑,还有就是首0和末尾0以及小数点没有处理好,下面贴代码,应该还可以优化一下, 比如乘数和被乘数如果是0,可以忽略,求指数也可以采用分治法,以后再有时间了补充吧
// bigMulMul.cpp : 定义控制台应用程序的入口点。 // #include "stdafx.h" #include <string> #include <iostream> using namespace std; string bigAdd(string a,string b) { int lena=a.length(); int lenb=b.length(); int dislen=lena-lenb; char cc[100]; string temp; int carry=0; if (lena>lenb) { for (int j=0 ;j<a.length();j++) { int c=0; if (j<lenb) c=(a[j]-'0'+b[j]-'0')+carry; else c=a[j]-'0'+carry; char tt[10]; sprintf(tt,"%d",c%10); temp+=tt; carry=c/10; } } if (lena<lenb) { for (int j=0 ;j<b.length();j++) { int c=0; if(j<lena) c=(b[j]-'0'+a[j]-'0')+carry; else c=b[j]-'0'+carry; char tt[10]; sprintf(tt,"%d",c%10); temp+=tt; carry=c/10; } } if (lena==lenb) { for (int j=0 ;j<a.length();j++) { int c=0; c=(a[j]-'0'+b[j]-'0')+carry; sprintf(cc,"%d",c%10); temp+=cc; carry=c/10; } } if (carry>0) { sprintf(cc,"%d",carry); temp+=cc; } return temp; } string bigMul(string a,string b) { int lena=a.length(); int lenb=b.length(); int apoint=lena-a.find('.')-1; int bpoint=lenb-b.find('.')-1; if (apoint==lena)apoint=0; if (bpoint==lenb)bpoint=0; char cc[100]; string temp; //store one mul result string total=""; //store all add result int ZeroNum=1;//store add zero num for (int i=a.length()-1;i>=0;i--) { int carry=0; if (a[i]=='.') continue; for (int j=b.length()-1;j>=0;j--) { if (b[j]=='.') continue; int t=(a[i]-'0')*(b[j]-'0')+carry; //add carry sprintf(cc,"%d",t%10); temp+=cc; carry=t/10; } if (carry>0) { sprintf(cc,"%d",carry); temp+=cc; } if (total.length()==0) { total=temp; }else { temp.insert(0,ZeroNum,'0'); //convenent for compute total=bigAdd(total,temp); ZeroNum++; } temp=""; } if (apoint!=0&&bpoint!=0) { if (apoint+bpoint>total.length()) { for (int i=0;i<apoint+bpoint-total.length();i++) { total+= "0"; } } total.insert(apoint+bpoint,"."); } string locals=""; for (int i=total.length()-1;i>=0;i--) { locals+=total[i]; } return locals; } string preProcess(string a ,int b) { string res; char temp[10000]={0}; int pos=a.find('.'); int i; for (i=0;i<a.length();i++) { if(a[i]!='0'&&i!=pos)break; } if (i==a.length()) { return "0"; } res=a; for (int i=0;i<b-1;i++) { res=bigMul(res,a); } int len=res.length(); while (res.length()>0)//去除前面的0 { if (res[0]!='0') { break; } res.erase(0,1); } if(res.find('.')!=-1) //必须有小数点才可以去除尾部的0 { for (int i=res.length()-1;i>=0;i--)//去除尾部的0 { if (res[i]!='0') { if(res[i]=='.') res.erase(i,1); break; } res.erase(i,1); } } return res; } int main(int argc, char* argv[]) { char R[1024]; int b; while(cin>>R>>b) { if (b==0) //如果b=0 ,任何数的0次方 =1 { cout<<"1"<<endl; return 0; } string temp=preProcess(R,b); if (temp.length()==1) { if (temp[0]=='.') { cout<<"0"<<endl; } cout<<temp[0]<<endl; }else { for (int i=0;i<temp.length();i++) { cout<<temp[i]; } cout<<endl; } } return 0; }