描述
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 Rnwhere R is a real number ( 0.0 < R < 99.999 ) and n is an integer such that 0 < n <= 25.
输入
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.
输出
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.
样例输入
95.123 12 0.4321 20 5.1234 15 6.7592 9 98.999 10 1.0100 12
样例输出
548815620517731830194541.899025343415715973535967221869852721 .00000005148554641076956121994511276767154838481760200726351203835429763013462401 43992025569.928573701266488041146654993318703707511666295476720493953024 29448126.764121021618164430206909037173276672 90429072743629540498.107596019456651774561044010001 1.126825030131969720661201
中文大意:
输入一系列的实数R(0.0 < R < 99.999),整数n( 0 < n <= 25);R占1-6列,n占8-9列
分别输出R^n;不要输出前导零和无意义的尾随零,若结果为整数不要输出小数点
思路:找出R的小数点并计算出小数点的位数,则结果小数点位数是其的n倍;去掉小数点之后就是整数之间的乘法,输出的时候把小数点带上
#include <cstdio>
#include <cstring>
int res[250];
void mult(int *a){
int tmp[250];
memset(tmp,0,sizeof(tmp));
for(int i=0;i<5;i++){
for(int j=0;j<250;j++)
tmp[i+j]+=a[i]*res[j];
}
for(int i=0;i<250;i++){
tmp[i+1]+=tmp[i]/10;
tmp[i]%=10;
}
memcpy(res,tmp,sizeof(tmp));
}
int main(){
char r[10];
int n,num[5];
while(scanf("%s%d",r,&n)!=EOF){
//找r中小数点
int point=0;
while(r[point]!='.')point++;
for(int i=point;i<5;i++)
r[i]=r[i+1];
//最后计算结果小数有(5-point)*n位
point=(5-point)*n;
for(int i=0;i<5;i++)
num[i]=r[4-i]-'0';
//result初始值为1,即个位为1
memset(res,0,sizeof(res));
res[0]=1;
while(n--)
mult(num);
//去掉前导零
int len=249;
while(len>=point&&res[len]==0)
len--;
//去掉小数点后的尾随零
int k=0;
while(k<point&&res[k]==0)
k++;
for(int i=len;i>=k;i--){
if(i==point-1&&k!=point)
printf(".");
printf("%d",res[i]);
}
printf("\n");
}
}
memcpy函数
void *memcpy(void *restrict s1,const void *restrict s2,size_t n)
从s2指向的位置拷贝n字节到s1指向的位置,而且都返回s1的值
带参数关键字restrict,即memcpy()假设两个内存区域之间没有重叠
用于处理任何数据类型,所以它的参数是两个指向void的指针,C允许把任何类型的指针赋值给void *类型的指针
sizeof(数组名)代表整个数组的字节数