编写一个执行数学计算的程序

Write a program that performs mathematical computation

我正在参加我的第一个编程 class,第二个实验室已经让我大吃一惊。

教授希望我们编写一个程序,该程序将从用户那里获取以英尺为单位的带小数点的测量值(输入),然后分别以英尺和英寸为单位显示该数字(输出)。

我对如何开始感到困惑。我们的结果假设看起来像“10.25 英尺等于 10 英尺 3 英寸”

这是我目前所拥有的:

print ("This program will convert your measurement (in feet) into feet and inches.")
print ()

# input section
userFeet = int(input("Enter feet: "))

# conversion
feet = ()
inches = feet * 12

#output section
print ("You are",userFeet, "tall.")
print (userFeet "feet is equivalent to" feet "feet" inches "inches")

而且我不知道从这里到哪里去。我了解将英尺转换为英寸,反之亦然。但我不明白分别从英尺转换为英尺和英寸。

如果可以请帮忙!谢谢!

您要打印的英尺数只是userFeet的整数部分。英寸是转换后的小数位。很像 200 分钟是 3 小时 20 分钟 ☺。所以:

from math import floor
print ("This program will convert your measurement (in feet) into feet and inches.")
print ()

# input section
userFeet = float(input("Enter feet: "))

# conversion
feet = floor(userFeet) # this function simply returns the integer part of whatever is passed to it
inches = (userFeet - feet) * 12

#output section
print("You are {} tall.".format(userFeet))
print("{0} feet is equivalent to {1} feet {2:.3f} inches".format(userFeet, feet, inches))

几个提示:

userFeet 不能是整数(因为它包含小数)。

脚数可以从 float/double 类型取整数。

英寸数可以通过将 userFeet 和英尺 (userFeet - feet) 的差值乘以 12 并四舍五入到最接近的整数来计算。

10.25 feet => 10feet + 0.25 feet => 10feet and 0.25*12inch => 10feet 3inch

所以取小数部分并乘以 12 得到以英寸为单位的结果,然后只显示英尺数和英寸数。

我会尝试通过对我所做更改的评论来修正您的代码。

import math # This is a module. This allows you to access more commands. You can see the full list of "math" commands with this link: https://docs.python.org/2/library/math.html

print ("This program will convert your measurement (in feet) into feet and inches.")
print ()

# input section
userFeet = float(input("Enter feet: ")) # You used integer, which would not support decimal numbers. Float values can, and it is noted with float()

# conversion
feet = math.floor(userFeet) # This uses the floor command, which is fully explained in the link.
inches = (userFeet - feet) * 12

#output section
print ("You are", str(userFeet), "tall.")
print (userFeet, "feet is equivalent to", feet, "feet", inches, "inches") # You forgot to add the commas in the print command.