1024. 科学计数法 (20)

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

 

 

 

利用字符串操作,思路见注释

 1 #include <iostream>
 2 #include <iomanip>
 3 #include <math.h>
 4 #include <stdio.h>
 5 #include <string>
 6 #include <string.h>
 7 #include <cstring>
 8 #include <cstdio>
 9 #include <algorithm>
10 #include <vector>
11 
12 using namespace std;
13 
14 int main()
15 {
16 
17     char s[9999];
18     scanf("%s", s);
19     int len = strlen(s);
20 
21     int idx;//E的下标
22     for (int i = 0; i < len; i++)
23     {
24         if (s[i] == 'E')
25         {
26             idx = i;
27             break;
28         }
29     }
30     int cnt_xs = idx-3;//小数点后面的位数
31     string a;
32     int j = 0;
33     char e[9999];//临时数组储存尾数
34     int fuhao_zhishu = (s[idx + 1] == '+') ? 1 : -1;//指数的符号
35     for (int i = idx + 2; i < len; i++)
36     {
37         e[j++] = s[i];
38     }
39     int zhishu = atoi(e);//字符串转换成整数
40 
41     for (int i = 1; i < idx; i++)//提取尾数部分为字符串a
42     {
43         a = a + s[i];
44     }
45     
46     
47     if (s[0] == '-')//只有当尾数符号为负时输出符号位
48         cout << '-';
49 
50     if (zhishu == 0)//相当于小数点不用移动
51     {
52         cout << a;
53     }
54 
55     else if (zhishu != 0)
56     {
57         a = a.replace(a.find('.'), 1, "");//删去尾数部分的小数点
58         if (zhishu*fuhao_zhishu < 0)//小数点左移时
59         {
60             if (zhishu == 1)//10^-1
61             {
62                 a = "0." + a;
63                 cout << a;
64             }
65             else
66             {
67                 for (int j = 0; j < zhishu - 1; j++)
68                     a = "0" + a;
69                 a = "0." + a;
70                 cout << a;
71             }
72         }
73         else//小数点右移时
74         {
75             if (zhishu < cnt_xs)//直接后移小数点
76             {
77                 a.insert(zhishu+1, ".");//插入小数点
78                 cout << a;
79             }
80             else if (zhishu == cnt_xs)//小数点加到末尾,相当于直接输出
81             {
82                 cout << a;
83             }
84             else//末尾加0
85             {
86                 for (int j = 0; j < zhishu - cnt_xs; j++)
87                     a = a + '0';
88                 cout << a;
89             }
90 
91         }
92         
93     }
94 
95 
96 
97     system("pause");
98     return 0;
99 }

 

posted @ 2017-03-18 20:51  NhdVW0V  阅读(269)  评论(0)    收藏  举报