POJ1001·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.

Sample Input

95.123 12
0.4321 20
5.1234 15
6.7592  9
98.999 10
1.0100 12

Sample Output

548815620517731830194541.899025343415715973535967221869852721
.00000005148554641076956121994511276767154838481760200726351203835429763013462401
43992025569.928573701266488041146654993318703707511666295476720493953024
29448126.764121021618164430206909037173276672
90429072743629540498.107596019456651774561044010001
1.126825030131969720661201

Hint

If you don't know how to determine wheather encounted the end of input:
s is a string and n is an integer

C++

while(cin>>s>>n)
{
...
}
c
while(scanf("%s%d",s,&n)==2) //to see if the scanf read in as many items as you want
/*while(scanf(%s%d",s,&n)!=EOF) //this also work */
{
...
}
#include <stdio.h>
#include <iostream>
#include <string>
using namespace std;

int main()
{
	string mlp;//乘数
	int power;//乘数的幂
	int r[151];//保存结果
	int hdot;//保存小数点位置 
	while(cin>>mlp>>power)
	{
		hdot=0;
		for(int t=0;t<150;t++)//初始化结果数组 
		{
			r[t]=-1;
		}
		if(mlp.find(".")!=string::npos)
		hdot=mlp.length()-mlp.find(".")-1;//记录小数点位置 
		string::iterator itr=mlp.end()-1;//迭代器指向最后一个字符 
		while(hdot>0&&itr>=mlp.begin())//去掉末尾无效的0 
		{
			if(*itr!='0')
			{break;}
			hdot--;
			itr--;
		}
		int cn=0;
		while(itr>=mlp.begin())//乘数第一次向结果数组中赋值 
		{
			if(*itr!='.')
			{
				r[cn]=*itr-'0';
				cn++;//结果数组长度或者说位数 
			}
		itr--;
		}
		int k=cn-1;
		int m=0;//保存临时数
		while(k>-1)
		{
			m=m*10+r[k];//乘数的逆序??? 
			k--;
		}
		for(int i=1;i<power;i++)//计算指数次方,方法很巧妙,自叹不如 
		{
			int j=0;
			while(r[j]>-1)
			{
				r[j]=r[j]*m;
				j++;
			}
			j=0;
			while(r[j]>-1)
			{
				if(r[j+1]==-1&&r[j]>=10)
					r[j+1]=r[j]/10;
				else
					r[j+1]+=r[j]/10;
				r[j]=r[j];
				j++;
			}
		} 
		hdot=hdot*power;//寻找小数点位置 
		int cnt=0;
		while(r[cnt]>-1)
		{
			cnt++;
		}
		if(hdot>=cnt)
		{
			cout<<".";
			while(hdot>cnt)
			{
				cout<<"0";
				hdot--;
			}
			hdot=0;
		}
		for(k=cnt-1;k>=0;k--)
		{
			if((k+1)==hdot&&hdot!=0)
			cout<<".";
			cout<<r[k];
		}
		cout<<endl;
	}
	return 0;
}
}
 

你可能感兴趣的:(POJ1001·Exponentiation)