编写执行数学计算的程序

时间:2016-06-28 08:02:34

标签: python math decimal computation

我参加了我的第一个编程课程,第二个实验室已经开始了我的屁股。

教授希望我们编写一个程序,以十进制(输入)的形式从用户那里获得测量结果,然后分别以英尺和英寸显示该数字(输出)。

我对如何开始感到困惑。我们的结果假设看起来像#10; 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")

我不知道从哪里开始。我知道将脚转换成英寸,反之亦然。但我不明白分开从英尺到英尺和英寸的转换。

请尽可能帮助!谢谢!

4 个答案:

答案 0 :(得分:1)

您要打印的脚只是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))

答案 1 :(得分:1)

我会尝试修改您的代码,并对我已更改的内容进行评论。

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.

答案 2 :(得分:0)

一些提示:

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

脚的数量可以从float / double类型浮动到整数。

可以通过将userFeet和feet(<html> .. <!-- marker_id_start --> .. html mark-up I want to keep... <!-- marker_id_end --> .. </html> )的差值乘以12并将其四舍五入为最接近的整数来计算英寸数。

答案 3 :(得分:0)

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

因此,取小数部分并乘以12得到英寸,然后只显示英尺数和英寸数。