POJ 1001 求高精度幂

题目描述:对数值很大、精度很高的数进行高精度计算是一类十分常见的问题。比如,对国债进行计算就是属于这类问题。 

现在要你解决的问题是:对一个实数R( 0.0 < R < 99.999 ),要求写程序精确计算 R 的 n 次方(Rn),其中n 是整数并且 0 < n <= 25。

解题思路:很简单的一道高精度题目。话不多说直接上代码,过程被写得复杂啦,有很大的改进空间。

#include <iostream>
#include <string>
using namespace std;

string multiple(string a, string b)  //计算两高精度数乘积
{
	int i, j;
	string result = "0";
	for(i = a.length() - 1; i >= 0; i--)
	{
		int remain = 0;
		string str = "";
		for(j = b.length() - 1; j >= 0; j--)
		{
			int tmp = (a[i] - '0') * (b[j] - '0') + remain;
			remain = tmp / 10;
			str = (char)(tmp % 10 + '0') + str;
		}
		if(remain != 0)
		{
			str = (char)(remain + '0') + str;
		}

		int tmp = 0;
		int m = result.length() - (a.length() - i);
		int n = str.length() - 1;
		remain = 0;
		while(m >= 0 && n >= 0)
		{
			tmp = (result[m] - '0') + (str[n] - '0') + remain;
			remain = tmp / 10;
			result[m] = (char)(tmp % 10 + '0');
			m--;
			n--;
		}

		while(m >= 0)
		{
			tmp = (result[m] - '0') + remain;
			remain = tmp / 10;
			result[m] = (char)(tmp % 10 + '0');
			m--;
		}

		while(n >= 0)
		{
			tmp = (str[n] - '0') + remain;
			remain = tmp / 10;
			result = (char)(tmp % 10 + '0') + result;
			n--;
		}

		if(remain != 0)
		{
			result = (char)(remain + '0') + result;
		}
	}

	return result;
}

int main()
{
	int n, i, j;
	string str;
	while(cin >> str >> n)
	{
		string res = "";
		int pos = str.find_first_of(".");

		if(pos != string::npos)
		{
			str.erase(pos, 1);
		}
		int num = str.length() - pos;

		if(n == 1) //计算str表示的数的n次幂
		{
			res = str;
		}
		else
		{
			res = multiple(str, str);
			for(i = 2; i < n; i++)
			{
				res = multiple(res, str);
			}
		}

		if(pos == string::npos)
		{
			cout << res << endl;
			continue;
		}

		int c = num * n;
		i = res.length() - 1;

		string s = "";
		while(c > 0 && i >= 0)
		{
			s = res[i--] + s;
			c--;
		}
		s = "." + s;

		for(j = 0; j <= i; j++)
		{
			if(res[j] != '0')
			{
				s = res.substr(j, i - j + 1) + s;
				break;
			}
		}

		for(i = s.length() - 1; i >= 0; i--)
		{
			if(s[i] == '0') //消除前导0
			{
				s.erase(i, 1);
			}
			else
			{
				break;
			}
		}
		if(s[s.length() - 1] == '.')
		{
			s.erase(s.length() - 1, 1);
		}

		cout << s << endl;
	}

	return 0;
}


你可能感兴趣的:(POJ 1001 求高精度幂)