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.
Sample Input
95.123 120.4321 205.1234 156.7592 998.999 101.0100 12
Sample Output
548815620517731830194541.899025343415715973535967221869852721.0000000514855464107695612199451127676715483848176020072635120383542976301346240143992025569.92857370126648804114665499331870370751166629547672049395302429448126.76412102161816443020690903717327667290429072743629540498.1075960194566517745610440100011.126825030131969720661201
分析:肯定不是不能用double和long double了,因為在相乘時會損失精度。所以用string類型來類比double的乘法和加法,只要按照手算的方法來實現就可以了(有兩個細節,剛開始我把數組反轉了,後來又把小數點去掉,這樣利於邏輯思維,當然也可以不用這用)
#include<iostream>#include<fstream>#include<vector>#include<string>#include<algorithm>#include<cmath>#include<string.h>using namespace std;//單個位相乘,累加到index開始的結果中void douMulOne(string &x,int index,char ch1,char ch2){while(index>x.size()){//把0加上x.push_back('0');}int one=ch1-'0';one =one*(ch2-'0');while(1){if(one==0)break;if(index<x.size()){one=one+(x[index]-'0');x[index]=one%10+'0';}else{x.push_back(one%10+'0');}one=one/10;index++;}}string douMul(string x1,string x2){//去掉小數點,簡化邏輯string::size_type count1 = x1.find('.');string::size_type count2 = x2.find('.');count1>=x1.size()?count1=0:count1=count1;count2>=x2.size()?count2=0:count2=count2;if(count1)x1.erase(x1.begin()+count1);if(count2)x2.erase(x2.begin()+count2);string result("0");for(string::size_type i=0;i<x2.size();i++){for(string::size_type j=0;j<x1.size();j++){douMulOne(result,i+j,x2[i],x1[j]);}//end for}//end forwhile(count1+count2>=result.size())result.push_back('0');if(count1+count2)//還原小數點result.insert(result.begin()+count1+count2,'.');return result;}void print(string sum){while(1){//按照格式輸出string::size_type count = sum.find('.');count>=sum.size()?count=0:count=count;if((sum[0]=='0'&&count>0)||sum[0]=='.')sum.erase(sum.begin());else if(sum[sum.size()-1]=='0')sum.erase(sum.end()-1);else break;}reverse(sum.begin(),sum.end());cout<<sum<<endl;}int main(){string r;int n;while(cin>>r>>n){string sum("1");//反轉,邏輯簡單reverse(r.begin(),r.end());while(n--)sum=douMul(sum,r);print(sum);}//end while}