逻辑错误 - 需要从1开始计算,而不是从2开始

时间:2014-03-25 02:01:19

标签: python

我试图让这个读取第一个'计数器',而不是将小时1计算为0.0。它应该在第一个小时计算速度。

如果我无法解释我的意思,请运行代码。你会注意到1(因为它打印一个长列表),第二个数字是0.0。假设我输入20为MPH和15为小时。打印时,这个20.0直到2号才出现。我需要它在1号弹出。我知道这是最基本的问题,但我无法弄明白:/

输出:

1   0.0

2   20.0

3   40.0

4   60.0

5   80.0

6   100.0

7   120.0

8   140.0

9   160.0

10   180.0

11   200.0

12   220.0

13   240.0

14   260.0

15   280.0

Distance traveled by Smith was 300 miles.

我的代码:

 def main ():

    greet()

    name = input("Please enter your name: ")
    print()

    speed = float(input("Please enter, in miles per hour, your speed (Between 20-500 MPH): "))

    while speed < 20 or speed > 500:
        print("You must enter a speed between 20-500 MPH")
        print()
        speed = float(input("Please try again: "))
        print()

    print("That speed is accepted.")
    print()

    time = int(input("Please enter, in hours, your travel time (Between 2-15 hours): "))    

    while time < 2 or time > 15:
        print("You must enter a time between 2-15 hours.")
        print()
        time = int(input("Please try again: "))
        print()

    print("That time is accepted.")
    print()

    totaldistance = speed * time
    totaldistance = int(totaldistance)

    for count in range (time):
        distance = speed * count
        print_data(name, distance, count, time)

    print()
    print("Distance traveled by", name,"was", totaldistance,"miles.") 

def greet ():
    print()
    print("This program calculates distance traveled.")
    print()

def print_data (name, distance, count, time):
    print()
    print(format(count + 1), " ", format(distance))

main() 

2 个答案:

答案 0 :(得分:0)

您的偏移是因为在count内向print_data添加1,但在计算距离时不会。

试试这个:

for count in range (1, time):
    distance = speed * count
    print_data(distance, count)

一起
def print_data (distance, count):
    print()
    print(count, distance)

答案 1 :(得分:0)

for count in range (time):
    distance = speed * count
    print_data(name, distance, count, time)

如果这是打印输出,那么您将从count的第一个值开始为0,因为它会启动范围。由于count = 0,因此speed * 0 = 0且print_data将始终为

print(format(1), " ", format(0))

作为第一个输出