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 6
la = 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;
}
}
}

本文介绍了一种使用数组实现的高精度乘法算法,以解决非常大数的幂运算问题。通过实例演示了如何将小数转换为整数进行计算,以及如何正确处理结果中的小数点、前置零和后置零。此算法适用于需要高精度计算的场景,如金融计算等。
1171

被折叠的 条评论
为什么被折叠?



