PTA乙级—1024 科学计数法 (20分)

1024 科学计数法 (20分)

科学计数法是科学家用来表示很大或很小的数字的一种方便的方法,其满足正则表达式 [±][1-9].[0-9]+E[±][0-9]+,即数字的整数部分只有 1 位,小数部分至少有 1 位,该数字及其指数部分的正负号即使对正数也必定明确给出。

现以科学计数法的格式给出实数 A,请编写程序按普通数字表示法输出 A,并保证所有有效位都被保留。

输入格式:

每个输入包含 1 个测试用例,即一个以科学计数法表示的实数 A。该数字的存储长度不超过 9999 字节,且其指数的绝对值不超过 9999。

输出格式:

对每个测试用例,在一行中按普通数字表示法输出 A,并保证所有有效位都被保留,包括末尾的 0。

输入样例 1:
`+1.23400E-03`
输出样例 1:
0.00123400
输入样例 2:
-1.2E+10
输出样例 2:
-12000000000

分析:直接从输出格式考虑

整体思路,将输入的科学计数法,视为字符串,分别处理小数部分和整数部分,再通过输出格式的几种情况分别去讨论。代码注释中有详细解释。

代码

#include<iostream>
#include <algorithm>
#include<cmath>
#include<iomanip>
using namespace std;

int main(){
   
   string num;
   cin>>num;
    int n = num.find('E');
    //小数部分
    string decimals = num.substr(0,n);
    //整数部分
    string exponent = num.substr(n+1);
    //第一个字符
    if(num[0]=='-'){
   
        cout<<num[0];
    }
    //如果指数部分为负,相对简单,
    if(exponent[0]=='-'){
   
        cout<<"0.";//前两个字符是“0.”(不包括负号)
        //小数部分前面补零
        for(int i =0;i<abs(stoi(exponent))-1;++i){
   
            cout<<"0";
        }
        //输出小数部门
        cout<<decimals.erase(2,1).erase(0,1);
    }else{
   
        //如果指数部分是正,相对复杂,需要考虑小数部分第一位是否为0
        //以及最后结果是整数还是小数
        //小数部分小于0时
        if(decimals[1]=='0'){
   

            string tem = decimals.erase(0,3);
            //再考虑小数点的位置
            if(stoi(exponent)>=tem.length()){
   
                cout<<tem;
                cout<<'.';
                for(int i = 0;i<stoi(exponent)-tem.length();++i){
   
                    cout<<'0';
                }
            }else{
   
                cout<<tem.insert(stoi(exponent),".");
            }
        }else{
   
            //小数部分大于0时
            string tem = decimals.erase(2,1).erase(0,1);
            //再考虑小数点的位置
            if(stoi(exponent)>=tem.length()-1){
   
                cout<<tem;
                for(int i = 0;i<stoi(exponent)-tem.length()+1;++i){
   
                    cout<<'0';
                }
            }else{
   
                cout<<tem.insert(stoi(exponent)+1,".");
            }
        }

    }
}
全部评论

相关推荐

点赞 收藏 评论
分享
牛客网
牛客企业服务