其他分享
首页 > 其他分享> > poj-1001Exponentiation 小数高精度幂运算

poj-1001Exponentiation 小数高精度幂运算

作者:互联网

这可以说是一个比较典型的小数幂指运算,另外还有整数的幂指运算,当然了今天写的代码即可有整数也可以有浮点数的幂指运算:
算法的具体实现过程是:把浮点型转化为整型,记录小数点的位置,然后使用一个数组a存储字符串,在用两个数组,一个数组c暂时存储当前算出的结果,b用来存储已有的结果(已经算出的),然后运用乘法算出第i次这个数与它已经乘出来的结果,考虑好c数组的进位后把c数组中的数转化到b中(因为b存储的是已经乘出来的结果),最后乘完m次后考虑输出时的前缀和后缀有0的部分;
题目:
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 R n 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

AC代码:

#include<stdio.h>
#include<string.h>
int a[4000],b[4000],c[4000];
char s[4000];
int main()
{
	int i,j,k,n,m,flag,point,len1;
	while(scanf("%s %d", s,&m)!=EOF)
	{
		memset(a,0,sizeof(a));
		int t=0;flag=0;
		int len=strlen(s);
		for(i=0; i<len; i++)//记录小数点的位置,并判断是否有小数点 
		{
			if(s[i]=='.')  
			{
			   flag=1;
			   break;	
			}
			t++;
		}
		if(flag==1)
		 len--;
		for(j=i; s[j]!='\0'; j++)//小数点后往前移 
		  s[j]=s[j+1];
		point=(len-t)*m;//小数点的位数(从后面算的) 
		for(i=0; i<len; i++)//将字符移到数组 
		  a[i]=s[len-i-1]-'0';
		  memset(b,0,sizeof(b));
		b[0]=1;
	    len1=1;
		for(i=1; i<=m; i++)
		{
			memset(c,0,sizeof(c));
			for(j=0; j<len; j++)//算出每次与自己相乘后的结果 
			  for(k=0; k<len1; k++)
			     c[k+j]+=a[j]*b[k];
		    for(k=0; k<len+len1; k++)
		    {
		    	c[k+1]+=c[k]/10;
		    	c[k]=c[k]%10;
			}
			memcpy(b,c,sizeof(c));
			len1+=len;
		}
		while(b[len1]==0) len1--;//扔掉前导零 
		for(i=len1; i>=point; i--)
		  printf("%d", b[i]);
		for(i=0; i<point; i++)//后导零问题 
		  if(b[i]!=0)
		  break;
		if(i<point)//如果去掉后面的0还有数的话就先输出小数点后依次将后面的数输出 
		{
			printf(".");
			for(j=point-1; j>=i; j--)
			 printf("%d", b[j]);
		}
		printf("\n");
	}
	return 0;
}

标签:int,value,will,4000,poj,1001Exponentiation,数组,exact,小数
来源: https://blog.csdn.net/weixin_44606952/article/details/99743595