1

我正在执行一项任务并且遇到了障碍。附上我的代码。这段代码的目的是在给定用户输入的起始重量、结束重量、起始高度和结束高度的情况下开发一个 bmi 表。我还附上了 BMI 计算器,它将根据体重和身高处理 BMI。BMI 计算器会将身高(以英寸为单位)转换为米,将体重(以磅为单位)转换为 KG。到目前为止,我的代码打印出垂直的重量和高度。问题是,我如何用适当的 BMI 填充内部?

def calculateBMI(height, weight):
    # This will process the parameters above and convert to 
    # meters and pounds accordingly.
    heightMeter = height * 0.0254

    # This will process weight into KG where 1 pound = .4536 KG
    weightKG = weight * 0.4536

    # Given the new converted numbers, this will then 
    # calculate BMI and return the output.
    calcBMI = (weightKG) / (heightMeter * heightMeter)
    return calcBMI

def printBMITable(startHeight, endHeight, startWeight, endWeight):
    for x in range (startWeight, endWeight + 1, 10):
        print "\t",x,
    print
    print

    for i in range(startHeight, endHeight + 1):
        print i
4

2 回答 2

1

使用rjust嵌套的for循环怎么样?rjust内置类型的方法str可以帮助您适应标签。例如,在我的终端上,制表符算作 8 个空格。并且打印逗号运算符会自动打印一个额外的空格。因此,我在以下代码中使用了rjust(8-1)or ,它在我的终端上打印得非常好:rjust(7)

def printBMITable(startHeight, endHeight, startWeight, endWeight):

    for x in range (startWeight, endWeight + 1, 10):
        print "\t",x,

    print '\n'

    for i in range(startHeight, endHeight + 1):
        print i,
        for x in range(startWeight, endWeight + 1, 10):
            print str(round(calculateBMI(i, x), 2)).rjust(7),
        print ''

输出:

>>> printBMITable(195, 200, 190, 200)
        190     200

195    3.51     3.7
196    3.48    3.66
197    3.44    3.62
198    3.41    3.59
199    3.37    3.55
200    3.34    3.52

请注意,在打印 BMI 时,我还使用了内置round函数来缩短小数位数。但是,您可以随意避免这种情况,或者将精度更改为您想要的任何小数位数。

于 2013-10-03T03:56:49.703 回答
0

你需要一个嵌套循环,基本上是这样的:

for weight in range(startWeight, endWeight):
    for height in range(startHeight, endHeight):
         #calculate BMI and print
于 2013-10-03T03:38:34.467 回答