⭐ 欢迎来到虫虫下载站! | 📦 资源下载 📁 资源专辑 ℹ️ 关于我们
⭐ 虫虫下载站

📄 高精度幂.cpp

📁 浮点数求高精度幂 poj2951 花了不少时间啊~~
💻 CPP
字号:
#include <iostream>
#include <cstring>
#include <cmath>
using namespace std;

char z[200]={0};
void Multi(char *p, char *q);
int main()
{
	char x[200]={0};
	double dmx,dtemp;
	int y;
	int i,j,bef,aft,key,lenx,lenz,mx,itemp;

	while (cin>>dmx>>y) 
	{
		i=0;
		bef=0;
		aft=0;
		dtemp=dmx;
		if (dtemp<0.001) dtemp+=0.001;
		else if (dtemp<0.01) dtemp+=0.01;
		else if (dtemp<1) dtemp+=1;
		
		while(fabs((double)dtemp-(int)dtemp) >= 1e-5 && fabs((double)dtemp-(int)dtemp-1) >= 1e-4)
		{
			
			dtemp*=10;
			aft++;
		}
		for (i = 0; i < aft; i++) dmx*=10;
		mx=ceil(dmx-0.00001);
		itemp=mx;
		while(itemp){itemp/=10;bef++;}
		x[bef]='\0';
		lenx=bef;
		while(mx)
		{
			bef--;
			x[bef]=mx%10+'0';
			mx/=10;
		}
		
		if (y==0) {cout<<"1"<<endl;continue;}
		else if (dmx == 0) {cout<<"0"<<endl;continue;}
		aft=aft*y;

		strcpy(z,x);
		for (i = 0; i < y-1;i++)
		{
			Multi(x,z);
		}

		lenz=strlen(z);	
		bef=lenz-aft;
		key=0;
		for (i = 0; i < lenz; i++)
		{
			if (aft>0)
			{
				if (bef < 0 && key == 0) 
				{
					cout<<".";
					for (j = 0; j > bef; j--) cout<<"0";
					key = 1;
				}
			
				if (i == bef) cout<<".";
			}
			cout<<z[i];
		}
		cout<<endl;
		memset(z,0,sizeof(z));
		memset(x,0,sizeof(x));
		
	}

	return 0;
}

void Multi(char x[200], char y[200])
{
	
	int a[200],b[200],m[200]={0},n[200]={0},c[200]={0};
	int lenx,leny,unitx,unity,sum;
	int i,j=0,k,l,s;
	int t=0;


	lenx=strlen(x);
	leny=strlen(y);
	unitx=lenx/4;
	unity=leny/4;
	sum=unitx+unity+1;

	
	for (i = lenx-1; i >= 0; i--)
	{	
		m[j++]=x[i]-'0';
	}

	j=0;

	for (i = leny-1; i >= 0; i--)
	{
		n[j++]=y[i]-'0';
	}
	for (i = 0,j = 0; i <= unitx+1; i++,j+=4)
	{
		a[i] = m[j] + m[j+1]*10 + m[j+2]*100 + m[j+3]*1e3;
	}
	
	for (i = 0,j = 0; i <= unity+1; i++,j+=4)
	{
		b[i] = n[j] + n[j+1]*10 + n[j+2]*100 + n[j+3]*1e3;
	}

	for (i = 0; i <= unitx; i++)
	{
		for (j = 0; j <= unity; j++)
		{
			s = c[i+j] + a[i]*b[j];
			if (s>=1e4)
			{
				c[i+j+1] += s/1e4;
			}
			c[i+j] = s % 10000;
			s = 0;
		}
	}
	while (c[sum]==0)
	{
		sum--;
	}
	
	for (i = sum; i >= 0; i--)
	{
		l=1;k=0;
		for (k = 3; k >= 0; k--)
		{
			l*=10;
			if (!(c[i]/l)) break;
		}
		
		for (j=3;j>=0;j--)
		{
			z[t+j]=c[i]%10+'0';
			c[i]/=10;
		}
		t=t+4;
	}
	z[t]='\0';

	i=0;
	while (z[i]=='0') i++;
	strcpy(z,&z[i]);
}



⌨️ 快捷键说明

复制代码 Ctrl + C
搜索代码 Ctrl + F
全屏模式 F11
切换主题 Ctrl + Shift + D
显示快捷键 ?
增大字号 Ctrl + =
减小字号 Ctrl + -