PAT 1073 Scientific Notation python解法

1073 Scientific Notation (20 分)
Scientific notation is the way that scientists easily handle very large numbers or very small numbers. The notation matches the regular expression [±][1-9].[0-9]+E[±][0-9]+ which means that the integer portion has exactly one digit, there is at least one digit in the fractional portion, and the number and its exponent’s signs are always provided even when they are positive.

Now given a real number A in scientific notation, you are supposed to print A in the conventional notation while keeping all the significant figures.

Input Specification:
Each input contains one test case. For each case, there is one line containing the real number A in scientific notation. The number is no more than 9999 bytes in length and the exponent’s absolute value is no more than 9999.

Output Specification:
For each test case, print in one line the input number A in the conventional notation, with all the significant figures kept, including trailing zeros.

Sample Input 1:
+1.23400E-03
Sample Output 1:
0.00123400
Sample Input 2:
-1.2E+10
Sample Output 2:
-12000000000

题意:将一个使用科学计数法形式的实数转换为正常的传统写法。
解题思路:
1.对所给数据进行切割,分别是底数的符号base_sign、底数base、指数的符号power_sign、指数power四部分。
2.找到小数点的位置point,也就是索引1的地方。
3.判断底数的符号base_sign是+还是-,如果是-,则在底数base前补指数power个0。
4.将底数base转为列表,删除小数点。
5.判断指数的符号power_sign,如果是-(也就是需要把小数点前移),则在底数base的索引1处插入一个小数点,如果是+(也就是需要把小数点后移),则分两种情况:如果小数点需要后移的位数point+int(power)超过了底数base的长度,需要在底数base后面补上point+int(power)-len(base)个0,否则只需把小数点插入到base的索引point+int(power)处。
6.最后判断一下如果底数的符号base_sign是-,则在base的最开始加上一个-。
7.输出base。

s = input()
base_sign = s[0]
for i in range(1,len(s)):
    if s[i] == 'E':
        split = i
        break
base = s[1:split]
power_sign = s[split+1]
power = s [split+2:]
#print(base_sign,base,power_sign,power)
for i in range(len(base)):
    if base[i] == '.':
        point = i
        
if power_sign == '-':
    base = '0'*int(power) + base
    
base = [i for i in base]
base.remove('.')

if power_sign == '-':
    base.insert(1,'.')
else:
    if point+int(power) >= len(base):
        base.extend('0'*(point+int(power)-len(base)))
    else:
        base.insert(point+int(power),'.')

if base_sign == '-':
    base.insert(0,'-') 
print(''.join(base))

猜你喜欢

转载自blog.csdn.net/qq_36936510/article/details/86432976