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

Python如何将用户输入关联坐标元组后作为参数传入自定义函数?

美国州间距离计算程序解决方法

你现有代码缺少三个关键部分:math模块导入、坐标与州名的映射结构、用户交互输入逻辑,调整后完整可运行代码如下:

import math

# 存储州名与对应坐标的映射字典,替代零散变量定义
state_coords = {
    "华盛顿特区": (38.9072, 77.0369),
    "北卡罗来纳州": (35.7596, 79.0193),
    "佛罗里达州": (27.6648, 81.5158),
    "夏威夷州": (19.8968, 155.5828),
    "加利福尼亚州": (36.7783, 119.4179),
    "犹他州": (39.3210, 111.0937)
}

print('本程序计算美国各州之间的距离(单位:英里)')
# 打印可选州列表,用序号选择降低输入错误概率
state_list = list(state_coords.keys())
print("可选州列表:")
for idx, state in enumerate(state_list, 1):
    print(f"{idx}. {state}")

def distance_calc(p1, p2):
    long_1 = p1[1] * math.pi/180
    lat_1 = p1[0] * math.pi/180
    long_2 = p2[1] * math.pi/180
    lat_2 = p2[0] * math.pi/180

    dlong = long_1 - long_2
    dlat = lat_1 - lat_2
    a = math.sin(dlat / 2) ** 2 + math.cos(lat_1) * math.cos(lat_2) * (math.sin(dlong / 2) ** 2)
    c = 2 * 3950 * math.asin(math.sqrt(a))
    result = round(c)
    print(f"两地距离为:{result} 英里")
    return result

# 输入校验逻辑,避免非法输入导致程序崩溃
while True:
    try:
        choice1 = int(input("请输入第一个州对应的序号:")) - 1
        choice2 = int(input("请输入第二个州对应的序号:")) - 1
        if 0 <= choice1 < len(state_list) and 0 <= choice2 < len(state_list):
            break
        else:
            print(f"请输入1到{len(state_list)}之间的有效序号")
    except ValueError:
        print("请输入合法的数字序号")

# 完成三者关联:用户选择的序号匹配到对应坐标,传入计算函数
p1 = state_coords[state_list[choice1]]
p2 = state_coords[state_list[choice2]]
distance_calc(p1, p2)

注意:美国本土经度为西经,现有坐标未添加负号,若计算结果和实际偏差过大,可将所有坐标的第二个值修改为负数即可

内容的提问来源于stack exchange,提问作者Christian Neal

相关产品推荐
方舟 Agent Plan

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

最近更新时间:2026.09.26 20:57:06