在codingame做的一道题

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)

评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值