您的位置:首页 > 其它

POJ 1001 Exponentiation

2009-12-08 22:40 459 查看
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

这是我做POJ的第一道题,看到Accept十分兴奋!终于品尝到AC的快乐!

#include<iostream>
#include<cstring>

using namespace std;

//用结构体来使代码更具可读性和可重复利用性
struct					Bigfloat
{
int					point;			//记录小数点后的位数
int					len;			//记录长度(除去小数点)
int					data[1000];		//储存数据的数组
//格式化输出函数
void print()
{

int				flag = 0;
while(data[flag]==0&&flag < point)    //设置标记点除去小数点后一些没用的0
{								      //同时当该数位整数时,也会自动去掉小数点
++flag;
}
if(data[len - 1] == 0)
--len;		  //除去首位为0
for(int i = len - 1;i >= flag;--i)
{
if(i == point - 1)
cout << ".";
cout << data[i];
}
cout << endl;
}
};
//高精度小数乘法的模板
Bigfloat				Multiply(Bigfloat a , Bigfloat b)
{
Bigfloat			temp;
temp.len = a.len + b.len;
temp.point = a.point + b.point;
memset(temp.data , 0 , sizeof(temp.data));

for(int i = 0;i < a.len;i++)
for(int j = 0;j < b.len;j++)
{
temp.data[i + j] += a.data[i] * b.data[j];
temp.data[i + j + 1] += temp.data[i + j] / 10;
temp.data[i + j] %= 10;
}
if(temp.data[temp.len - 1] == 0)
temp.len --;
return temp;
}
//倒位的函数,方便调用
Bigfloat				Change(char s[])
{
Bigfloat			data;
data.len = strlen(s) - 1;
memset(data.data, 0 , sizeof(data.data));

for(int i = 0,j = 0;i < strlen(s);++i,++j)
{
if(s[strlen(s) - i - 1] == '.')
{
++i;
data.data[j] = s[strlen(s) - i - 1] - '0';
data.point = j;
}
else
{
data.data[j] = s[strlen(s) - i - 1] - '0';
}
}
return data;
}

int						main()
{
int					n;
Bigfloat			a,b;
char				num[1000];
while(cin >> num >> n)			//通过循环利用模板完成幂乘
{
a = Change(num);
b = a;
for(int i = 1;i < n;++i)
{
Multiply(a,b);
a = Multiply(a,b);
}
a.print();
}
return 0;

}
[/code]
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: