A1073 Scientific Notation (20 分| 字符串处理,附详细注释,逻辑分析)

写在前面

  • 思路分析
    • 给出科学计数法格式的数字A,要求输出普通数字表示法的A,并保证所有效位都被保留,包括末尾的0
    • 实现分析:
      • n保存E后面的字符串所对应的数字, t保存E前⾯的字符串串,不包括符号位
      • 当n<0时表示向前移动,那么先输出0.然后输出abs(n)-1个0,然后继续输出t中的所有数字;
      • 当n>0时候表示向后移动,那么先输出第1个字符,然后将t中尽可能输出n个字符
      • 如果t已经输出到最后⼀个字符(j == t.length())那么就在后面补n-cnt个0,否则就补充1个小数点。 然后继续输出t剩余的没有输出的字符
  • 题目基础,容易实现
    • 细节处理耗费时间(下标处理)

测试用例

  • input:
    +1.23400E-03
    output:
    0.00123400
    intput:
    -1.2E+10
    output:
    -12000000000
    

ac代码

  • #include <iostream>
    using namespace std;
    int main()
    {
        string s;
        cin >> s;
        int i = 0;
        while (s[i] != 'E') i++;
        string t = s.substr(1, i-1);
        int n = stoi(s.substr(i+1));
        if (s[0] == '-') cout << "-";
        if (n < 0)
        {
            cout << "0.";
            for (int j = 0; j < abs(n) - 1; j++) cout << '0';
            for (int j = 0; j < t.length(); j++)
                if (t[j] != '.') cout << t[j];
        }
        else
        {
            cout << t[0];
            int cnt, j;
            for (j = 2, cnt = 0; j < t.length() && cnt < n; j++, cnt++) cout <<
                        t[j];
            if (j == t.length())
                for (int k = 0; k < n - cnt; k++) cout << '0';
            else
            {
                cout << '.';
                for (int k = j; k < t.length(); k++) cout << t[k];
            }
        }
        return 0;
    }
    
发布了328 篇原创文章 · 获赞 107 · 访问量 39万+

猜你喜欢

转载自blog.csdn.net/qq_24452475/article/details/100620478
今日推荐