首页 > 试题广场 >

Are They Equal (25)

[编程题]Are They Equal (25)
  • 热度指数:8415 时间限制:C/C++ 1秒,其他语言2秒 空间限制:C/C++ 64M,其他语言128M
  • 算法知识视频讲解
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.

输入描述:
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.


输出描述:
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.d1...dN*10^k" (d1>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.
示例1

输入

3 12300 12358.9

输出

YES 0.123*10^5
对这道破题,我要好好写一下解答思路
import math as t
a = input().split()
try:m = t.log(eval(a[1]),10)
except:m = 0;
try:n = t.log(eval(a[2]),10)
except:n = 0
m = int(m) - 1 if m < 0 else int(m)
n = int(n) - 1 if n < 0 else int(n)
a[1] = a[1].replace('.','')
a[2] = a[2].replace('.','')
c = '{:0<' + str(a[0]) + '}'
for i in range(len(a[1])):
    if a[1][i] != '0':
        a[1] = '0.' + c.format(int(a[1][i:i + int(a[0])])) + '*10^' + str(m + 1)
        break
else:
    a[1] = '0.' + c.format(int(a[1][i:i + int(a[0])])) + '*10^' + str(m)
for i in range(len(a[2])):
    if a[2][i] != '0':
        a[2] = '0.' + c.format(int(a[2][i:i + int(a[0])])) + '*10^' + str(n + 1)
        break
else:
    a[2] = '0.' + c.format(int(a[2][i:i + int(a[0])])) + '*10^' + str(n)
if a[1] == a[2]:
    print('YES',a[1])
else:
    print('NO',a[1],a[2]) 
首先,获取两数的以10为底的对数的整数值(由于处理近似的机制限制,负数值要减少1),如果两数有值为0的话就直接返回0(牛客第一个用例);
其次,既然记录了两数的对数值就知道其大小,因此可去掉数中的小数点和非有效数字0,得到两个裸数;
再次,根据题目要求输出的格式,转化成:“0.” + “裸数(根据要求有效位数,可能只输出数前方一部分,也可能不够要在其后补0)” + “*10^” + “对数值 + 1”的结果;
最后,比较两结果是否相等,然后再相应输出就行了。

切忌对两数进行运算,有精度影响。


编辑于 2020-02-19 20:38:44 回复(0)