【问题标题】:Write a program that performs mathematical computation编写一个执行数学计算的程序
【发布时间】:2016-10-30 10:33:46
【问题描述】:

我正在上我的第一堂编程课,而第二个实验室已经让我大吃一惊。

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

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

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

如果可以,请提供帮助!谢谢!

【问题讨论】:

标签: python math decimal computation


【解决方案1】:

我将尝试使用 cmets 将您的代码修改为我已更改的内容。

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】:

    您将打印的英尺只是 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))
    

    【讨论】:

      【解决方案3】:

      几个提示:

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

      英尺数可以从float/double类型下限为整数。

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

      【讨论】:

        【解决方案4】:
        10.25 feet => 10feet + 0.25 feet => 10feet and 0.25*12inch => 10feet 3inch
        

        所以取小数部分并乘以 12 得到英寸,然后将英尺数和英寸数一起显示。

        【讨论】:

          猜你喜欢
          • 2019-07-12
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          • 2021-12-10
          • 1970-01-01
          • 2022-08-17
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多