Write a program that prints the temperature closest to 0 among input data. If two numbers are equally close to zero, positive integer has to be considered closest to zero (for instance, if the temperatures are -5 and 5, then display 5).
编写一个程序,在输入数据中打印最接近 0 的温度。如果两个数字同样接近零,则必须认为正整数最接近零(例如,如果温度为 -5 和 5,则显示 5)。
我的答案:
# 读取温度数量
n = int(input())
# 读取温度字符串并将其拆分为整数列表
temperatures = list(map(int, input().split()))
# 如果没有提供温度值,打印0并退出程序
if n == 0:
print(0)
exit()
# 将最接近的温度初始化为列表中的第一个温度值
closest_temperature = temperatures[0]
# 遍历温度列表以找到最接近的温度值
for temp in temperatures:
# 比较绝对值以找到最接近的温度值
if abs(temp) < abs(closest_temperature) or (abs(temp) == abs(closest_temperature) and temp > closest_temperature):
closest_temperature = temp
# 打印最接近的温度值
print(closest_temperature)