想在python中将cm^3转换为L

2024-04-28 05:28:33 发布

您现在位置:Python中文网/ 问答频道 /正文

我想写一个函数,当我输入一个截锥(一个杯子)的尺寸和一个以升为单位的液体量时,返回这些杯子中可以装满多少液体的量。我知道1L=1000 cm^3,但我不知道我如何将它合并到我的代码中,以返回我期望的结果

def number_of_cups(bottom_radius, top_radius, height, litres_of_liquid):
    volume = math.pi / 3 * height * (bottom_radius**2 + top_radius * bottom_radius +  top_radius**2)


    return int(filled_cup)   

就我所知,我知道我很接近,但我不知道如何形容我的转变


Tags: of函数代码number尺寸topdefcm
3条回答

把我自己的答案扔到桩上:

#!/usr/bin/python2
import math

# nothing about units here , but let's say it's cm
def cup_vol(b_rad=3, t_rad=4, h=5):  
    vol = math.pi/3 * (b_rad**2 + t_rad + b_rad + t_rad**2) * h
    return vol

def n_cups(liquid_amount, whole_cups=True):  # nothing about units here

    # liquid amount is Liter then first convert it to CM^3
    liquid_amount = liquid_amount*1000
    # this yields an int
    if whole_cups:
        return int(liquid_amount/cup_vol())
    # else, return a real number with fraction
    return liquid_amount/cup_vol() 


if __name__ == '__main__':
    print "4L fill %f cups" % n_cups(4)
    print "4L fill %f cups (real)" % n_cups(4, whole_cups=False)

运行上述脚本将产生:

4L fill 23.000000 cups
4L fill 23.873241 cups (real)

好吧,我想指出的是,你的体积计算好像错了。你知道吗

def number_of_cups(bottom_radius, top_radius, height, litres_of_liquid):  
    volume = 4 * math.pi * height * (bottom_radius**2 + top_radius**2)/2  
    filled_cup = 1000 * litres_of_liquid / volume  
    return int(filled_cup)

如果你不知道的话,除法在Python2和Python3中是不同的。你知道吗

Python 2

>>> 1/2
0

Python 3

>>> 1/2
0.5
>>> 1//2
0

这取决于给定底部半径、顶部半径和高度的单位。如果我们假设这些长度以厘米为单位,那么

def number_of_cups(bottom_radius, top_radius, height, litres_of_liquid):
    volume = math.pi / 3 * height * (bottom_radius**2 + top_radius * bottom_radius +  top_radius**2)
    return int( litres_of_liquid * 1000 / volume )

litres_of_liquid * 1000是升转换成厘米^3。int()可以用math.floor()替换,如果要计算完全装满的杯子的数量,math.ceil()将给出装满或部分装满的杯子的数量。你知道吗

最后,还有一个很好的包magnitude,它封装了一个物理量。如果用户想要指定不同的长度单位,您可以使用这个包。你知道吗

OP所述公式是正确的。你知道吗

相关问题 更多 >