当前位置: 代码迷 >> 综合 >> 2008年西电机试 Problem E
  详细解决方案

2008年西电机试 Problem E

热度:104   发布时间:2023-10-23 04:13:30.0

1.问题描述

请写一个程序,计算Rn精确结果(0.0<R<99.999,n是整数且0<n<=25)。

2.输入说明

有多组数据,每组数据占一行,用一对数据表示,第一个数据是R(含小数点共6位),第二个数据是n,两个数之间有一个空格。

3.输出说明

每个输入输出其结果(占一行)

4.输入样本

    95.123 12
    0.4321 20
    5.1234 15
    6.7592  9
    98.999 10
    1.0100 12

5.输出样本

548815620517731830194541.899025343415715973535967221869852721

.00000005148554641076956121994511276767154838481760200726351203835429763013462401 

43992025569.928573701266488041146654993318703707511666295476720493953024

29448126.764121021618164430206909037173276672

90429072743629540498.107596019456651774561044010001

1.126825030131969720661201

6.思路分析

(1)问题转化

最开始我没有读懂题目,后面才知道这就是幂运算,即计算R^n;

(2)问题求解

  • a.将R(浮点型,我代码采用的字符串)转化为整型num(R最多只有6位数,所以够用),即将R小数点去掉;
  • b.用一个大型数组result[1000]记录运算结果的每一位的值,并且初始化为0,只有各位为1(因为1*a=a);
  • c.然后计算result与num的乘积(见函数Multiply(xxxx)),注意用len记录当前运算结果所使用的位数,注意进位问题;
  • d.规范化运算结果result数组
  •        i.确定小数点的位置;
  •        ii.小数点最低位的0,不用输出来(如1.100000,只打印1.1)。

7.C++代码实现

#include<iostream>
#include<vector> using namespace std;
int* Multiply(int *result, int data, int &len)  
// result为运算结果,data乘数,len当前运算结果所占的位数 
{  // 获取整数各位数字之和 int carry = 0, i = 0; // carry进位// 计算结果result与R的乘积 for(i = 0; i < len; i++){result[i] = result[i] * data + carry;carry = result[i] / 10;result[i] = result[i] % 10;}// 进位while(carry)  // 若进位不为零,则一直进位 {result[i++] = carry % 10;carry = carry / 10;} len = i;  // i从0开始的,所有i++后,才是当前乘法后的位数。 return result;} int main()
{string R;     int n;          vector <string> vec;while(cin>>R>>n){int len = 1;  // 初始化运算结果所占位数 int num, position;     // num为浮点数R转化为整数,position为小数部分的位数 int *result = new int[1000];// 结果容器初始化 for(int i = 0; i < 100; i++)result[i] = 0;result[0] = 1;          position = R.find(".");// 去除小数点的字符串 R = R.substr(0, position).append(R.substr(position+1, R.size()));num = stoi(R);position = (R.size() - position) * n; // 结果小数点位数 // 计算n次幂,其中不包括小数点 for(int j = 0; j < n; j++)result = Multiply(result, num, len);// 规格化运算结果 string str = "";    // 记录最终规范化后的结果if (len < position) // 小数位数大于积位数,添加0 {str += '.';     // 添加小数点str.append(position-len, '0');  // 小数点后面用0填充 }int start_index = 0;                // 记录最低位非零的位置 while (start_index < position && result[start_index] == 0) // 找到小数最低位的非零位置start_index++; for(int i = len - 1; i>=start_index; i--){if (len > position && i == position - 1)str += '.';char temp = result[i] + 48;    // 将数字(0~9)转化为字符('0'~'9') str +=  temp;}vec.push_back(str); }// 遍历动态数组,并且打印结果 vector <string>::iterator t;for(t=vec.begin(); t!=vec.end();t++)cout<<*t<<endl;return 0;} 

 

 

 

  相关解决方案