本文主要是介绍POJ 1001 Exponentiation 求高精度幂,希望对大家解决编程问题提供一定的参考价值,需要的开发者们随着小编来一起学习吧!
题目链接
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.
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<iostream>
#include<stdio.h>
#include<string>
using namespace std;
int a[1001], b[1001];//保存相乘的2个高精度实数
int tmp[10001];//保存临时结果
int la, lb;
void mul() {//两个高精度实数相乘for (int i = 0; i <= 10000; i++)tmp[i] = 0;//注意每次相乘都要事先将临时结果初始化!for (int i = 0; i < la; i++) {for (int j = 0; j < lb; j++) {tmp[i + j] += a[i] * b[j];if (tmp[i + j] > 9) {tmp[i + j + 1] += tmp[i + j] / 10;tmp[i + j] %= 10;}}}//按照可能的最大长度来保存la += lb;for (int i = 0; i < la; i++) {a[i] = tmp[i];}
}
int main() {char s[10]; int n;while (scanf("%s %d", s, &n) != EOF) {int pos = -1; int j = 0;//pos用于保存小数点的位置for (int i = 5; i >= 0; i--) {if (s[i] == '.') {pos = i;}else {a[j] = s[i] - '0';b[j] = a[j];j++;}}//j为5or 6la = lb = j;for (int t = 1; t < n; t++) {mul();}int l = 0, r = la - 1;pos = (lb - pos)*n;//小数点的位置if (lb == 6) {//无小数点的情况for (int i = la - 1; i >= 0; i--) {cout << a[i];}cout << endl;continue;}else {while (a[l] == 0 && l <= r) { l++; }//后置零while (a[r] == 0 && r >= l) { r--; }//前置零if (r < pos) { r = pos - 1; }if (l > pos) { l = pos; pos = -1; }//cout << pos << endl;for (int i = r; i >= l; i--) {if (i == pos-1) {//因为从位置0出开始保存,因此小数点与pos-1处的数字前cout << ".";}cout << a[i];}cout << endl;}}
}
这篇关于POJ 1001 Exponentiation 求高精度幂的文章就介绍到这儿,希望我们推荐的文章对编程师们有所帮助!