1024 科学计数法

题意不难理解,但是做起来比较麻烦。

用的string的erase(迭代器),find(字符串)返回pos和substr.

给出的数用str存放,如果是负数,就输出'-',否则不输出。然后用erase移除第一个符号,无论正负。

然后把str按照E划分成两个部分,前半部为a,后半部为e。

如果e < 0 ,输出 e个0以及小数点,最后输出a

如果e >= 0,第一,输出a的每个字符,只有在下标 i == e 并且 i 不是最后一字符的下标,才输出小数点,比如1.2E+1;输出是12。第二,如果 e > a.length(),那么就输出后面的0,这里好难描述,在草稿纸上画一下就清楚了。

#include<iostream>
using namespace std;

int main() {
    string str,a,b;
    cin>>str;
    if(str[0] == '-')
        cout<<str[0];
    str.erase(str.begin());
    int pos = str.find('E');
    a = str.substr(0,pos);
    a.erase(a.begin()+a.find('.'));
    b = str.substr(pos+1,-1);
    int e = stoi(b);
    if(e < 0) {
        e = 0-e;
        for(int i = 0 ; i < e; ++i) {
            if(i == 1)
                cout<<'.';
            cout<<0;
        }
        cout<<a;
    } else {
        int i = 0;
        for( ; i < a.length(); ++i) {
            cout<<a[i];
            if(i == e && i < a.length()-1)//下标e处且不是最后一个字符,就输出小数点。如果a.length()<e,那么这一步肯定不会执行。 
                cout<<'.';
        }
        while(i++ <= e)//如果a.length()<e,后面全部输出0
            cout<<0;
    }
    return 0;
}

 

posted @ 2020-02-16 18:42  tangq123  阅读(200)  评论(0编辑  收藏  举报