1. 程式人生 > >PAT 1073 Scientific Notation[字符串處理][科學記數法]

PAT 1073 Scientific Notation[字符串處理][科學記數法]

ping each vid ini nal ssi osi view tex

1073 Scientific Notation(20 分)

Scientific notation is the way that scientists easily handle very large numbers or very small numbers. The notation matches the regular expression [+-][1-9].[0-9]+E[+-][0-9]+ which means that the integer portion has exactly one digit, there is at least one digit in the fractional portion, and the number and its exponent‘s signs are always provided even when they are positive.

Now given a real number A in scientific notation, you are supposed to print A in the conventional notation while keeping all the significant figures.

Input Specification:

Each input contains one test case. For each case, there is one line containing the real number A in scientific notation. The number is no more than 9999 bytes in length and the exponent‘s absolute value is no more than 9999.

Output Specification:

For each test case, print in one line the input number A in the conventional notation, with all the significant figures kept, including trailing zeros.

Sample Input 1:

+1.23400E-03

Sample Output 1:

0.00123400

Sample Input 2:

-1.2E+10

Sample Output 2:

-12000000000

題目大意:將科學記數法轉換為正常表示的數。由於給的範圍都比較大,肯定只能用字符串來表示了

//之前見過一道科學記數法的題目呢,最關鍵的就是小數點的位置和首位非0元的位置。

pat上一次就AC,牛客網上也通過了,開心。

#include <iostream>
#include<stdlib.h>
#include <string>
#include<cmath>
using namespace std;

int main()
{
    string s;
    cin>>s;
    //找到指數。
    int pos=s.find("E");
    int expo=atoi(s.substr(pos+1).c_str());
    //如果指數是負數,那麽就往前加0;
    if(expo<0){
        int p=s.find(".");
        s.erase(p,1);
        s.insert(1,"0.");
        int to=abs(expo)+2;
        for(int i=3;i<to;i++){
            s.insert(i,"0");
        }
        s=s.substr(0,pos+abs(expo));
        //cout<<s;

    }else if(expo>0){
        //找到小數點後有幾位
        int len=pos-3;
       // cout<<len<<‘\n‘;
        if(len>expo){
            s.insert(expo+3,".");
            s.erase(2,1);
            s=s.substr(0,pos);
        }else{//len<=expo
            int p=expo-len;
            s=s.substr(0,pos);
            for(int i=0;i<p;i++){
                s+="0";//怎麽把0放進去呢?
            }
            s.erase(2,1);
        }

    }
    if(s[0]==+)
        s=s.substr(1);
    cout<<s;
    return 0;
}
//  +1.2345E03
//  -1.2E+10

主要就是幾種情況的考慮:

1.當指數<0的時候,往前補0就可以了

2.當指數>0的時候,分兩種情況:一種是小數點後的位數=<指數的,那麽需要去小數點後,在後面補0;另一種是小數點後的位數>指數的,那麽需要挪動小數點就可以了。

3.對stoi和atoi有了更深的認識,我用的編譯器,不支持stoi(頭文件為#include<string>),而支持aoti(頭文件為#include<stdlib.h>)

4.atoi(s.substr(pos+1).c_str());因為後者是C中的函數,那麽需要對字符串進行轉換成C中形式,就是調用c_str()函數。

另外還有一點,我的代碼中並沒有判斷指數為0的情況。。明顯樣例中並沒有給出這樣的情況:

技術分享圖片

。。。

查看了柳神的代碼:https://www.liuchuo.net/archives/2061

進行了判斷指數是否為0。

PAT 1073 Scientific Notation[字符串處理][科學記數法]