If a machine can save only 3 significant digits, the float numbers 12300 and 12358.9 are considered equal since they are both saved as 0.123×105 with simple chopping. Now given the number of significant digits on a machine and two float numbers, you are supposed to tell if they are treated equal in that machine.
Input Specification:
Each input file contains one test case which gives three numbers N, A and B, where N (<100) is the number of significant digits, and A and B are the two float numbers to be compared. Each float number is non-negative, no greater than 10100, and that its total digit number is less than 100.
Output Specification:
For each test case, print in a line YES
if the two numbers are treated equal, and then the number in the standard form 0.d[1]...d[N]*10^k
(d[1]
>0 unless the number is 0); or NO
if they are not treated equal, and then the two numbers in their standard form. All the terms must be separated by a space, with no extra space at the end of a line.
Note: Simple chopping is assumed without rounding.
Sample Input 1:
3 12300 12358.9
Sample Output 1:
YES 0.123*10^5
Sample Input 2:
3 120 128
Sample Output 2:
NO 0.120*10^3 0.128*10^3
题目大意
给定N,A,B三个数字,将A和B转换成科学计数法,要求保留N位小数,如果转换出来的结果相同,则输出YES和转换结果,否知输出NO和A、B的转换结果。
分析
本来想用format()函数转换成科学计数法,然后进行格式化输出,但是format()的缺陷是超过6位就不精确了,所以还是老实来吧。
把数字分为四类,进行不同的处理:
1>等于0. 最简单的,直接格式化输出字符串
2>小于1但是大于0.获取科学计数法的小数和指数部分
3>大于1但是包含小数点的。先去除掉小数点前一个0之前的所有0。(考虑00000.123这个例子)去除小数点,并在最前面加上'0.',并在最后加上N个0
4>大于1且没有小数点的,去除掉前面所有的0(考虑0005这个例子)。在前面加上'0.',在后面加上N个'0'。
最后输出的格式是统一的,w是指数,而q因为最后都加了N个0,所以输出q[:n+2]。
Python实现
def change(num, n):
if float(num) < 1:
if float(num) == 0:
q = '0.'+'0'*n
w = 0
else:
a = str(int(num[2:]))
w = -(len(num) - 2 - len(a))
q = '0.' + a + '0'*n
else:
start = 0
if '.' in num:
for x in range(len(num)):
if num[x+1] == '.' or int(num[x]) >0:
break
num = num[x:]
w = num.find('.')
q = '0.'+num.replace('.' ,'') + '0'*n
else:
for x in range(len(num)):
if int(num[x]) > 0:
break
num = num[x:]
w = len(num)
q = '0.'+num+'0'*n
return '{}*10^{}'.format(q[:n+2], w)
if __name__ == "__main__":
line = input().split(" ")
n = int(line[0])
a, b = line[1], line[2]
first, second = change(a, n), change(b, n)
if first == second:
print("YES", first)
else:
print("NO", first, second)