高精度乘单精度 poj1001

   这道题也是一道简单的高精度乘单精度,但需要注意的细节很多(wrong了六次大哭)。要注意的部分已在代码中标出。奋斗

//高精度乘单精度
#include<iostream>
#include<cstdio>
#include<cstring>

using namespace std;
int ans[10000000];
int pos;//小数点的位置

int main()
{
	char s[10];
	int n,i,j,b,len;
	while(~scanf("%s%d",s,&n))
	{
		i=b=pos=0;
		while(s[i]!='\0')
		{
			if(s[i]=='.')
				pos=strlen(s)-i-1;
			else
				b=b*10+(s[i]-'0');
			i++;
		}
		if(pos!=0)//去掉小数末尾的0
		{
			while(b%10==0&&pos)//很重要的判断(pos不能等于0)
			{
				b/=10;
				pos--;
			}
		}
		len=0;
		i=b;
		while(i)//初始化ans[]
		{
			ans[++len]=i%10;
			i/=10;
		}
		for(i=2;i<=n;i++)
		{
			for(j=1;j<=len;j++)
			{
				ans[j]=ans[j]*b+ans[j-1]/10;
				ans[j-1]%=10;
			}
			while(ans[len]>=10)
			{
				len++;
				ans[len]=ans[len-1]/10;
				ans[len-1]%=10;
			}
		}
		pos*=n;
		for(i=len;i>pos;i--)//整数部分
			printf("%d",ans[i]);
		if(pos)
			printf(".");
		if(pos>len)//小数位数不够,补0
		{
			for(i=pos;i>len;i--)
				printf("0");
			pos=len;
		}
		for(i=pos;i>=1;i--)//小数部分
			printf("%d",ans[i]);
		printf("\n");
	}
	return 0;
}


 

你可能感兴趣的:(高精度乘单精度 poj1001)