简体   繁体   English

函数和随机整数

[英]Functions and random integers

I want to first say this is my homework, so I do not want it done for me I just need some guidance as my teacher is not providing it for me nor can I find my answer online. 我首先要说这是我的作业,所以我不想为我完成它,我只需要一些指导,因为我的老师没有为我提供它,我也无法在线找到答案。 Here is my problem 这是我的问题

Write a program that displays a table of distance equivalents in miles and kilometers. 编写一个程序,以英里和公里为单位显示距离等效表。 You must generate the table by running a function inside a loop in main. 您必须通过在main的循环内运行一个函数来生成表。 Generate a random integer from 10 to 60, inclusive, in each loop cycle. 在每个循环周期中生成一个10到60(含)之间的随机整数。 Use this latter value as the miles argument to the function. 使用后一个值作为函数的Miles参数。 The function must then print a line in the table. 然后,该函数必须在表格中打印一行。 Repeat: The function prints the table. 重复:该功能打印表格。

I am able to get the top part of the table to print correctly. 我可以使表格的顶部正确打印。 When I run my code at the top it gives me the calculation for the kilometers but then just prints the same number 10 times. 当我在顶部运行代码时,它会为我提供公里数的计算,但是只打印相同的数字10次。

How do I get it to print out the 10 random numbers for the miles and the calculations in the right spot for the kilometers? 如何获得打印出来的10个随机数字的英里数和正确的公里数计算结果?

Example output: 输出示例:

  MILES   KILOMETERS
52.00     83.68568
11.00     17.70274
40.00     64.37360
21.00     33.79614
14.00     22.53076
23.00     37.01482
48.00     77.24832
22.00     35.40548
15.00     24.14010
16.00     25.74944

obviously the sample output is supposed to be in two different columns for the miles and the kilometers but I couldn't figure out how to set that up on here. 显然,样本输出应该在英里和公里的两个不同的列中,但是我不知道如何在此处进行设置。

my code 我的代码

import random
  def main():
      print('Miles\tKilometers')
      miles = random.randint(10, 60)
      find_kilometers(miles)
      for number in range(10):
      print(miles)



 def find_kilometers(miles):
         kilometers = miles * 1.60934
         print(format(kilometers, '.5f'))

main() 

Probably a bit late for your homework, but I'll answer anyway. 您的作业可能要迟一点,但是我还是会回答。

You're assigning the value for miles outside of your for loop, so it's going to use that single value 10 times. 您正在为for循环之外的miles分配值,因此它将使用该单个值10次。

Also I'm assuming that it's just a typo in your post but the print(miles) line should be indented so it's within the for loop. 我还假设这只是您的帖子中的错字,但应该将print(miles)行缩进,使其位于for循环内。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM