1. 程式人生 > 其它 >EOJ 2995. 科學計數法 個人解題記錄

EOJ 2995. 科學計數法 個人解題記錄

2995. 科學計數法

題幹

任給一個十進位制正數 M>0 (M 可能為整數或小數,且最多包含 200 位數字)。寫一個程式將其轉換成科學計數法表示,形式為 aFb。其中 1≤a<10 且不含前置 0,a 的長度為給定精度 p (p 包括 a 中整數及小數部分但不包含小數點)。a 的值由四捨五入方法確定,M 中有效數字長度小於 p 時,後面填充 0 補足。b 為指數,b=0 時,省略指數部分。

輸入格式

第 1 行:一個整數 T(1≤T≤10)為問題數。

每組測試資料為一行,包含兩個數字,之間由一個空格分開。第一個數字是待轉換數字 M,第二個數字是要求的輸出精度 p (1<p≤30)。

輸出格式

對於每個問題,輸出一行問題的編號(0 開始編號,格式:case #0: 等)。

然後接下來一行中輸出給定數字的科學計數法表示。

樣例

input

3
123456789 8
0.0045678 3
1.8 4

output

case #0:
1.2345679F8
case #1:
4.57F-3
case #2:
1.800

繁瑣的程式碼
#include <iostream>
#include <string>
#include <string.h>
using namespace std;
int main()
{
    int ti, ret = 0;
    cin >> ti;
    while (ti--)
    {
        printf("case #%d:\n", ret++);
        string a, b;
        int f, num;
        cin >> a >> num;
        if (a[0] == '-')
        {
            a.erase(a.begin());
            cout << "-";//符號判斷
        }
        if (a.find('.') == -1)
        {
            a = a + '.';
        }
        a = '0' + a;            //奇怪的步驟,但可以防止999變2位精度時不能得到1.0F3,留空給進位用
        int head = a.find('.'); //原本的小數點位在head-1處
        int temphead = head;
        string::iterator it = a.begin();
        while (temphead--)
        {
            it++;
        }
        a.erase(it); //除去小數點;
        a = a + "00000000000000000000000000000000000000000000000000000000000000000000000000000";
        int prezero = 0;
        for (int i = 0; a[i] != '\0'; i++)
        {
            if (a[i] == '0')
            {
                prezero++;
                continue;
            }
            break;
        }
        // cout << "test data::prezero ->" << prezero << endl; //實際上都多了1位
        int res = 1;
        // cout << "The number we determine add---" << a[prezero + num] << endl;//判斷是否該進位
        // cout << "first:" << a << endl;
        if (a[prezero + num] >= '5')
            for (int i = prezero + num - 1; i >= prezero - 1; i--)
            {
                if (a[i] == '9' & res == 1)
                {
                    a[i] = '0';
                    res = 1;
                    continue;
                }
                a[i] = a[i] + res;
                res = 0;
            } //精確度操作
        // cout << "lasto:" << a;//測試精度轉換成功否?
        int prezero2 = 0; //重新統計0
        for (int i = 0; a[i] != '\0'; i++)
        {
            if (a[i] == '0')
            {
                prezero2++;
                continue;
            }
            break;
        }

        int tail = head - prezero2 - 1;//尾數
        // cout<<tail<<endl;
        for (int i = prezero2; i < prezero2 + num; i++)
        {
            cout << a[i];
            if (i == prezero2)
                cout << ".";
        }
        if (tail != 0)
            cout << "F" << tail;//為零就不輸出
            cout<<endl;
    }
}
//我的部落格主頁在https://www.cnblogs.com/emokable/
//思路:對真分數和假分數一起判斷,前置0用於進位,用string容器的find()找出'.'的位置
//用了兩次前置0,第一次用來定位判斷進位,第二次則是找到輸出位置(因為進位後前置0變化)
> ps:自己做了這道題,理清思路就不難了