# POJ1001 Exponentiation【高精度乘方】

672人阅读 评论(0)

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

#include <iostream>
#include <string>

using namespace std;

int len; // total length of exponentiation result存储乘方结果的总长度
int product[126] = {0}; //存储结果，最大长度为5*25+1=126（5是99.999有5个数字，25是n的最大值，+1是加的小数点）（可以试一下，99.999的平方是10个数字+一个小数点哦）

void multiply(int a[], int n){
int i;
int carry = 0; // a carry number in multiplying
for (i = 0; i < len; i++){
int temp = a[i]*n + carry;
a[i] = temp % 10;
carry = temp / 10;
}
while (carry){
a[i] = carry % 10;
i++;
carry /= 10;
}
len = i;
}

int main(){
int n;  // power n
char s[6]; // real number R, at most the length is 6
while (cin>>s>>n){
int position=0, i=0, num=0, j=0;
for (i=0; i<strlen(s); i++) {
if (s[i] == '.'){
position = (strlen(s) - 1 - i) * n; // calculate decimal point position in
//  in R^n，因为结果数组是倒着放的，所以.的位置要用小数来算
}
else{
num = num*10 + s[i] - '0'; // transfer float to integer
}
}

// product calculation
product[0]=1;
len = 1;
for (i = 0; i < n; i++){
multiply(product, num);
}

// format output
if (len <= position){ // product is less than 1
printf("."); // print decimal point
for (i=0; i<position-len; i++){
printf("0"); // print zero between decimal point and decimal
}

j = 0;
while (product[j] == 0){ // trim trailing zeros
j++;
}
for (i=len-1; i>=j; i--){
printf("%d", product[i]);
}
}
else{
j=0;
while (product[j]==0 && j<position){ // trim trailing zeros
j++;
}
for (i=len-1; i>=j; i--){
if (i+1 == position){ // cause index in C language starts from 0
printf(".");
}
printf("%d", product[i]);
}
}
printf("\n");
}
system("pause");
return 0;
}

/*
poj 1001
version:1.0
author:Knight
Email:S.Knight.Work@gmail.com
*/

#include<cstdio>
#include<cstring>
#include<cstdlib>
#include<memory.h>
using namespace std;

char Result[200];//存R^N的结果

//大实数的乘法,乘数为FirMultiplier和SecMultiplier，结果存在Result中
void HigRealMul(char* FirMultiplier, char* SecMultiplier, char* Result);
//剔除实数尾部的无效0或小数点
void CutInsignificantTail(char* StrR);
//计算小数点在实数中的位数
int CountPointIndex(char* StrR);
//删除实数中的小数点,PointIndex为小数点在实数中从右向左数的第几位
void DeletePoint(char* StrR, int PointIndex);

int main(void)
{
char StrR[10];//R对应的字符串
int N;
int i;
int PointIndex = 0;//记录小数点在实数中从右向左数的第几位，如1.26在第3位，4在第0位

while(scanf("%s%d", StrR, &N) != EOF)
{
memset(Result, 0, 200);

CutInsignificantTail(StrR);

PointIndex = CountPointIndex(StrR);

DeletePoint(StrR, PointIndex);

strcpy(Result, StrR);

for (i=2; i<=N; i++)
{
HigRealMul(Result, StrR, Result);
}

int Len = strlen(Result);

if (Len -(PointIndex - 1) * N < 0)
{
printf(".");
for (i = Len - (PointIndex - 1) * N; i<0; i++)
{
printf("0");
}
}

for (i=0; i<Len; i++)
{
//输出小数点
if (i == Len -(PointIndex - 1) * N)
{
printf(".");
}
printf("%c", Result[i]);
}
printf("\n");
//printf("%s\n", Result);
//printf("%d\n", PointIndex);
}
return 0;
}

//大实数的乘法,乘数为FirMultiplier和SecMultiplier，结果存在Result中
void HigRealMul(char* FirMultiplier, char* SecMultiplier, char* Result)
{

char TmpResult[200];
int i,j;
int k = -1;//控制TmpResult[]下标
int FirLen = strlen(FirMultiplier);
int SecLen = strlen(SecMultiplier);

memset(TmpResult, '0', 200);

//模拟乘法运算
for (i=SecLen-1; i>=0; i--)
{
k++;

int FirMul;
int SecMul = SecMultiplier[i] - '0';
int Carry;//进位

for (j=FirLen-1; j>=0; j--)
{
FirMul = FirMultiplier[j] - '0';
TmpResult[k + FirLen - 1 - j] +=   FirMul * SecMul % 10;
Carry = FirMul * SecMul / 10 + (TmpResult[k + FirLen - 1 - j] - '0') / 10;
TmpResult[k + FirLen - 1 - j] = (TmpResult[k + FirLen - 1 - j] - '0') % 10 + '0';
TmpResult[k + FirLen - j] += Carry;
}
}

//防止某一位的值超过9
for (k=0; k<200; k++)
{
TmpResult[k + 1] += (TmpResult[k] - '0') / 10;
TmpResult[k] = (TmpResult[k] - '0') % 10 + '0';
}
//将设置字符串结束符
for (k=199; k>=0; k--)
{
if ('0' != TmpResult[k - 1])
{
TmpResult[k] = '\0';
break;
}
}

//将临时存储的答案TmpResult倒转变成我们熟悉的方式，存到Result中
for (i=strlen(TmpResult)-1,j=0; i>=0; i--,j++)
{
Result[j] = TmpResult[i];
}
Result[j] = '\0';

}

//剔除实数尾部的无效0或小数点
void CutInsignificantTail(char* StrR)
{
int i;
int PointIndex = CountPointIndex(StrR);
int Len = strlen(StrR);

if (0 == PointIndex)
{
if ('.' == StrR[Len - 1])
{
StrR[Len - 1] = '\0';
}

return;
}

for (i=Len-1; i>Len-1-PointIndex; i--)
{
if ('0' == StrR[i] || '.' == StrR[i])
{
StrR[i] = '\0';
}
else
{
return ;
}
}
}

//计算小数点在实数中的位数
int CountPointIndex(char* StrR)
{
int i;
int Index = 0;

for (i = strlen(StrR); i>=0; i--)
{

if ('.' == StrR[i])
{
break;
}
else
{
Index++;
}
}

if (-1 == i)
{
Index = 0;
}

return Index;

}

//删除实数中的小数点
void DeletePoint(char* StrR, int PointIndex)
{
int i;
int Len = strlen(StrR);

for (i=strlen(StrR)-PointIndex; i<Len; i++)
{
StrR[i] = StrR[i+1];
}
}

C++中将string类型转换为int, float, double类型

# 方法一： 使用stringstream

stringstream在int或float类型转换为string类型的方法中已经介绍过， 这里也能用作将string类型转换为常用的数值类型。

Demo:

[cpp] view plain
1. #include <iostream>
2. #include <sstream>    //使用stringstream需要引入这个头文件
3. using namespace std;
4.
5. //模板函数：将string类型变量转换为常用的数值类型（此方法具有普遍适用性）
6. template <class Type>
7. Type stringToNum(const string& str)
8. {
9.     istringstream iss(str);
10.     Type num;
11.     iss >> num;
12.     return num;
13. }
14.
15. int main(int argc, char* argv[])
16. {
17.     string str("00801");
18.     cout << stringToNum<int>(str) << endl;
19.
20.     system("pause");
21.     return 0;
22. }

 801 请按任意键继续. . .

#方法二：使用atoi()、 atil() 、atof()函数  -----------------实际上是char类型向数值类型的转换

1. atoi():      int atoi ( const char * str );

Demo：

[cpp] view plain
1. #include <iostream>
2. using namespace std;
3. int main ()
4. {
5.     int i;
6.     char szInput [256];
7.     cout<<"Enter a number: "<<endl;
8.     fgets ( szInput, 256, stdin );
9.     i = atoi (szInput);
10.     cout<<"The value entered is :"<<szInput<<endl;
11.     cout<<" The number convert is:"<<i<<endl;
12.     return 0;
13. }

 Enter a number: 48 The value entered is : 48 The number convert is: 48

2.aotl():  long int atol ( const char * str );

3.atof():  double atof ( const char * str );

Demo：

[cpp] view plain
1. /* atof example: sine calculator */
2. #include <stdio.h>
3. #include <stdlib.h>
4. #include <math.h>
5. int main ()
6. {
7.   double n,m;
8.   double pi=3.1415926535;
9.   char szInput [256];
10.   printf ( "Enter degrees: " );
11.   gets ( szInput );
12.   //char类型转换为double类型
13.   n = atof ( szInput );
14.   m = sin (n*pi/180);
15.   printf ( "The sine of %f degrees is %f\n" , n, m );
16.
17.   return 0;
18. }

0
0

个人资料
• 访问：283657次
• 积分：5981
• 等级：
• 排名：第5132名
• 原创：342篇
• 转载：81篇
• 译文：1篇
• 评论：38条
博客专栏
 leetcode 文章：234篇 阅读：45411
文章分类