以下是此作业的说明:
编写一个名为carpet.py的程序,该程序使用名为carpet_cost的void函数来计算和显示地毯矩形房间的成本。该功能应以房间的长度为单位,以英尺为单位的房间宽度,以及每平方码的地毯成本作为参数。应从主函数中的用户输入获得这三个值。 carpet_cost函数应以货币格式计算并显示地毯的成本,其中$符号与第一个数字相对应,如果数量为千位,则为逗号分隔符,小数点后两位。
这是我到目前为止所拥有的,
length = int(input("What is the length of tbe room you're trying to carpet?: "))
width = int(input("What is the width of tbe room you're trying to carpet?: "))
cost = int(input("What is the cost per square yard of tbe room you're trying to carpet?: "))
def carpet_cost(total_cost):
total_cost == ((length * width) / 3) * cost
print('The cost to carpet this room will be $', format(total_cost, ',.2f'))
carpet_cost(total_cost)
我在如何使其成为无效功能方面遇到了麻烦,我试图到处寻找,但我还没有找到办法让它成功。我确实知道如何使用简单的方法通过仅使用一个函数来计算它,但我真的很困惑void函数如何帮助提供相同的输出。
如果我的代码不好,那么任何帮助都会受到赞赏和抱歉,但这是因为我很难绕过无效功能。
答案 0 :(得分:3)
如果通过" void"你的意思是"没有返回任何东西",你已经有了无效功能。
您的carpet_cost
函数需要一个参数total_cost
,但它应该采用三个参数来计算每平方码的长度,宽度和成本。此外,您应该使用赋值运算符=
而不是相等测试运算符==
。
length = int(input("What is the length of tbe room you're trying to carpet?: "))
width = int(input("What is the width of tbe room you're trying to carpet?: "))
cost = int(input("What is the cost per square yard of tbe room you're trying to carpet?: "))
def carpet_cost(l,w,c):
total_cost = ((l * w) / 3) * c
print('The cost to carpet this room will be $', format(total_cost, ',.2f'))
carpet_cost(length,width,cost)
结果:
What is the length of tbe room you're trying to carpet?: 3
What is the width of tbe room you're trying to carpet?: 3
What is the cost per square yard of tbe room you're trying to carpet?: 50
The cost to carpet this room will be $ 150.00
此外,在计算总成本时,您似乎遇到了算术问题。如果你想将平方英尺转换成平方码,你必须除以9,而不是三。
答案 1 :(得分:0)
其中一个肯定可能是你想要的
#example 1
def carpet_cost(length,width,cost_per_unit):
return length*width*cost_per_unit
print carpet_cost(length=5,width=10,cost_per_unit=2.10)
#example 1.0005
def carpet_cost(length,width,cost_per_unit):
print length*width*cost_per_unit
#example 2 (pass by reference, since a list is editable)
def carpet_cost(args_list):
length,width,cost_per_unit = args_list
args_list[:] = [length*width*cost_per_unit]
length,width,cost = 5,10,1.12
result = [length,width,cost] # a list is editable
carpet_cost(result)
print result
答案 2 :(得分:-1)
见Python void-like function。 Python是动态类型的,它的函数总会返回一些东西。如果您没有指定返回值,python会自动返回None
。
此外,您有total_cost
作为carpet_cost
的参数,这是计算total_cost
的函数。我想你需要检查一下你的逻辑。