You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Python中接收负数作为输入?附坐标计算代码示例

解决Python接收负数输入并计算坐标距离的问题

你的代码当前的问题在于直接遍历输入字符串的每个字符来转换整数,这会导致负数的负号被当作单独字符处理,引发转换错误,而且无法正确识别用空格分隔的多个坐标值。正确的处理方式是先将输入按空格分割为独立的数字字符串,再转换为整数。

修正后的代码如下:

import math
# 获取输入并按空格分割,转换为整数列表
x_coordinates = [int(x) for x in input("Enter the x coordinates: ").split()]
y_coordinates = [int(y) for y in input("Enter the y coordinates: ").split()]

# 计算两点间距离(假设输入的是两个坐标,取首尾元素)
total_x = (x_coordinates[-1] - x_coordinates[0]) ** 2
total_y = (y_coordinates[-1] - y_coordinates[0]) ** 2
distance = math.sqrt(total_x + total_y)
print(distance)

关键说明:

  • 使用split()方法:默认按任意空白字符(空格、制表符等)分割输入字符串,能正确提取包括负数在内的每个数字字符串,比如输入-5 10会被分割为["-5", "10"]。
  • 列表推导式直接转换:将分割后的每个字符串元素转换为整数,这样就能正确处理负数。

内容的提问来源于stack exchange,提问作者Sohaila Ali

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.20 21:57:32