【问题标题】:How to take multiple integers with spaces as input?如何将多个带空格的整数作为输入?
【发布时间】:2014-04-01 20:32:32
【问题描述】:

我必须取 3 个用空格分隔的整数输入,例如。 3 4 5 并从下一个中减去每个后续的。例如 4 中的 3 和 5 中的 4,然后将结果相加。

有人知道我会怎么做吗,如果你有兴趣,我被问到这个问题:

Lineland 是一个伟大的无限国家,位于牛轴上。莱茵兰共有三个城市。 A市坐标xA,B市坐标xB,C市坐标xC。

一个旅行者Chloe住在A市。她想严格按照这个顺序先去B市,然后再去C市。但要为这次旅行做准备,她现在需要提前准备旅行的距离。

给定坐标 xA, xB, xC,求 Chloe 从城市 A 到城市 B,然后从城市 B 到城市 C 必须经过的距离。

输入 第一行包含三个以空格分隔的整数:xA, xB, xC (1 ≤ xA, xB, xC ≤ 100) — 城市 A、B 和 C 的坐标。

输出 打印一个整数 - Chloe 从 A 市到 B 市,然后从 B 市到 C 市必须经过的距离。

【问题讨论】:

    标签: python input integer


    【解决方案1】:

    您的输入将采用字符串形式,您可以使用 str.split(sep) 拆分字符串

    def distance(start,end):
        # I'll leave implementation of this to you
        # use the distance formula if you want to impress your teacher
        # but since Lineland lies entirely upon one axis, this shouldn't
        # be very hard for you :)
    
    # if in_ is your input
    xA, xB, xC = in_.split(" ")
    # you could also do = map(int,in_.split(" ")) to avoid the int() calls below
    # but frankly I think using the map function is a lesson better suited for
    # later.
    chloes_travel_time = distance(int(xA),int(xB)) + distance(int(xB),int(xC))
    
    print(chloes_travel_time)
    

    【讨论】:

    • 嗨,谢谢你的回答,但我不确定如何检查它是否是一个整数,以及数字是随机的,所以我必须使用 raw_input,有什么想法吗?
    • @MitchellDoesntCare 不太确定你在问什么。你通过调用int来检查它是否是一个整数,如果它不是一个整数,它会抛出一个ValueError。无论您使用raw_input(用于Python2)还是input(用于Python3)都无关紧要
    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2021-12-07
    • 1970-01-01
    • 2020-04-07
    • 2015-05-19
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多