【问题标题】:how do i know if the logic of my programme right?我怎么知道我的程序的逻辑是否正确?
【发布时间】:2019-09-05 18:45:27
【问题描述】:

我的作业是编写一个计算出租车费用的程序。但是,出租车收取 2.00 英镑的基本票价,前五英里每英里每英里 2.00 英镑,之后每英里每英里 1.00 英镑。并且老师给了我们一个提示说我们可以把计算票价的部分写成一个函数

这就是我所做的... 没有错误,但唯一的问题是我的程序在输入任何距离时都不起作用

user_fare = int(input('Please enter the distance '))
if user_fare == 0:
    print('2')
elif user_fare > 0 and user_fare < 5:
    def distance_into_money(fare):
        return ((user_fare*2)+2)
        print(distance_into_money)
elif user_fare > 5:
    def distance_into_money(fare):
        return ((user_fare*2)+1)
        print(distance_into_money)
else:
    print('Error')

我预计 1 英里的输出为“4.00 英镑”,6 英里的输出为“13.00 英镑”,-1 英里的输出为“错误”,但我的程序没有输出

【问题讨论】:

  • 如何确定?正如老师所说,编写一个以距离为参数并返回票价的函数。然后,(手动)计算几个有代表性的距离(例如 0、1、2.5、4、5、6、7、10、50 英里)的正确值,并验证所有这些距离的结果是否正确。另外,谷歌unittest
  • 这两个elif 语句定义了函数,但它们不运行它们。这些定义有其自身的问题。 return 后面的print 无法执行。

标签: python python-3.x python-2.7 ipython


【解决方案1】:

函数 distance_into_money 应该在你的逻辑语句之外定义。对你来说,一开始就将逻辑应用到该函数中会更好。

让我们也重新设计你的逻辑:

  1. 5 英里以下,票价为 2 美元(基础)+2 美元/英里。
  2. 超过 5 英里,票价为 2 美元(基本)+ 2 美元/英里 * 5 美元(5 英里)+ 1 美元/英里(5 英里以上每英里)。将这一切重新处理到您的代码中,我们得到
# Defining our function first allows us to use it later.
# None of the code in the function is executed until you call the function later
def distance_into_money(dist):
    if 0 <= dist <= 5: # Python supports logical statements like this
        return 2 + (dist*2)
    if dist > 5:
        return 2 + (2*5) + 1*(dist-5)
        # Again, this is $2 base + $2/mil * 5 mil + $1/mi * (number of miles over 5 miles)
    return -1 # Indicates there was an error: The dist was not in the acceptable bounds

users_distance = int(input("Please enter the distance "))
users_fare = distance_into_money(users_distance)
if users_fare == -1: # There was an error
    print("Error")
else: #There was not an error
    print("The user's fare is ${}".format(users_fare))

# The str.format method replaces the {} with its argument (which is the user's fare in this case).

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2019-07-16
    • 2013-03-25
    • 1970-01-01
    • 2010-09-20
    • 1970-01-01
    相关资源
    最近更新 更多