简单题POJ-1001,大数乘法

/*

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.

*/

#include <iostream>
#include <string>

using namespace std;

//整数大数乘法->OK
void Multiplication(char strNum1[],char strNum2[])
{
	 int Length1 = strlen(strNum1);
	 int Length2 = strlen(strNum2);

	 //存放结果,但是其位序为倒序
	 char result[200] = "";

	 for(int i=Length2-1; i>=0; --i)

	 {
		 // 乘数逐位iNum,乘进位数iMul,结果组下标k
		 int iNum = strNum2[i] - '0';
		 int iMul = 0;
		 int k = 0;

		 //逐位相乘
		 for(int j=Length1-1; j>=0; --j,k++)
		 {
			iMul = iNum * (strNum1[j] - '0') + iMul;

			if(result[k + Length2 - i -1] != 0)
				result[k + Length2 - i -1] += iMul%10;
			else
				result[k + Length2 - i -1] += (iMul%10 + '0');
			
			if(result[k + Length2 - i -1]>'9')
			{
				 result[k + Length2 - i -1] -=10;
				 iMul+=10;
			}

			iMul/=10;
		 }

		 if(iMul)
			result[k + Length2 - i -1] = iMul + '0';

	}

	int n = 0;
	
	for(int m = strlen(result)-1; m>=0; --m,++n)
		strNum1[n] = result[m];
	
	strNum1[n] = 0;
}

 

 

//寻找小数点,并去除->OK
int searchPoint(char strNum[])
{
	int i;
	int flag = 0;
	int pos;
	int lengeth = strlen(strNum);
	for( i=0; i<lengeth; ++i)
	{
		if(strNum[i]=='.')
		{
			flag = 1;
			pos = lengeth - i - 1;
		}

		strNum[i] = strNum[i+flag];
	}
	strNum[i] = 0;
	return pos;
}

 

//标准化,并插入小数点->

void Standardization(char strNum[],int pos,int n)
{
	int length = strlen(strNum);
	int dis = 0;
	int i;

	for( i=0; i<length-pos*n; ++i)
	{
		if(strNum[i]=='0')
			dis++ ;
		else
			break;
	}

	for( i=0; i<length-pos*n-dis; ++i)
		strNum[i] = strNum[i+dis];
	
	int k = i;
	
	//不移,左移,右移
	if(dis==1);
	else if(dis==0)
	{
		for( i=length; i>k; --i)
			strNum[i] = strNum[i-1];
	}
	else
	{
		for( i=k+1; i<length-dis+1; ++i)
			strNum[i] = strNum[i+dis-1];
	}
	strNum[k] = '.';
	strNum[length-dis+1] = 0;

	int j;
	for( j=length-dis;j>=k;--j)
	{
		if(strNum[j]=='0' || strNum[j]=='.')
			strNum[j] = 0;
		else
			break;
	}
}

 

int main()
{
	char R[7];
	char Result[200] = "";
	int  n;
	int pos;
	while(cin>>R>>n)
	{
		pos = searchPoint(R);
		strcpy_s(Result,R);
		for(int i=n-1; i>0; --i)
			Multiplication(Result,R);
		Standardization(Result,pos,n);
		cout<<Result<<endl;
	}
	return 0;
}

点赞