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<string>
using namespace std;
int main()
{
    string s;
    int z = 0;
    cin >> s;
    if (s[0] == '-')cout << '-';
    string s1(s, 1, s.find('E') - 1);//s1是E前面的部分
    int it = s.find('E') + 2;
    string s2(s, it);//s2是E后面的部分
    z = stoi(s2);
    if (z == 0) {
        cout << s1; system("pause"); return 0;
    }
    /******************************************/
    string ss(s1);
    ss.replace(s1.find('.'), 1, "");//remove the point, all those possibilites need to do this this move is dengrous, because you change the length of the s1, so I use the copy of the s1. if you have to change an important value, make a copy of it in case you use the poperty of the old one which hasn't been changed.
    if (s[it - 1] == '-') {//小数点往左走
        ss.insert(0, "0.");
        ss.insert(2, z - 1, '0');
        cout << ss;
    }
    else if (z + 2 < s1.length()) {//小数点没出去
        ss.insert(z+1,1,'.');
        cout << ss;
    }
    else {
        ss.append(z - (s1.length() - s1.find('.')) + 1, '0');//逻辑比较饶。
        cout << ss;
    }
    system("pause");
}

这是一个让我受益匪浅的题目,这才叫真正的字符串处理。
1.string 从里一个 string 里初始化:string s(s1,pos)//pos是代表位置,从此位置以后的s1拷贝到s中。
2.string的操作:insert,replace , append(insert可以代替)
insert(pos,arg)pos之前,
replace(pos,len,arg)
最基础的用法:字符串就不要管,如果插得是字符,则要加一个参数n。
即 arg=(n,c)或(srt)

猜你喜欢

转载自blog.csdn.net/sc_jn/article/details/78235721