如何在python 3.3.4中编写一个计算矩形面积的程序?
声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow
原文地址: http://stackoverflow.com/questions/21880810/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me):
StackOverFlow
How to write a program in python 3.3.4 that works out the area of a rectangle?
提问by user3316570
How do you write a program that works out the area of a rectangle, by collecting the height and width of the rectangle from the user input, calculates the area and displays the result? How would you do it with the volume for a cuboid as well? My code so far is: (I've just started python)
你如何编写一个程序来计算矩形的面积,通过从用户输入中收集矩形的高度和宽度,计算面积并显示结果?你会如何处理长方体的体积?到目前为止,我的代码是:(我刚刚开始使用 python)
shape = input("> ")
height = input("Please enter the height: ")
width = input("please enter the width: ")
area = [height*width]
print ("The area is", 'area')
But I am receiving invalid syntax.
但我收到无效的语法。
采纳答案by thefourtheye
In Python 3.x, inputreturns a string. So, both heightand widthare strings.
在 Python 3.x 中,input返回一个字符串。所以,height和width都是字符串。
area = [height*width]
You are multiplying strings here and creating a list. You need to convert them to either integers (with intfunction) or floating point numbers (with floatfunction), like this
您在这里乘以字符串并创建一个列表。您需要将它们转换为整数(带int函数)或浮点数(带float函数),就像这样
height = float(input("Please enter the height: "))
width = float(input("please enter the width: "))
...
area = height*width
And then, its better to pass a single string to the printfunction, like this
然后,最好将单个字符串传递给print函数,就像这样
print ("The area is {}".format(area))
Or you can simply print the items like this
或者您可以简单地打印这样的项目
print ("The area is", area)
回答by gravetii
print ("The area is", area)
and you don't need to store the area in a list - area = height * widthis enough.
并且您不需要将该区域存储在列表中 -area = height * width就足够了。
Just do it similarly to calculate the volume of a cuboid:
只需类似地计算长方体的体积:
l = int(input("Please enter the length: "))
h = int(input("Please enter the height: "))
w = int(input("please enter the width: "))
vol = l*h*w
print ("The volume is", vol)
Notice that you need to convert the user input to an intbefore trying to do any math with them.
请注意,int在尝试对它们进行任何数学运算之前,您需要将用户输入转换为 an 。
回答by user3100799
make sure that the user is only able to enter floats and not strings else you will get an error:
确保用户只能输入浮点数而不是字符串,否则你会得到一个错误:
height = float(input("What is the height?")
once you have both of the inputs then to output:
一旦你有两个输入然后输出:
area = height * width
print("The area is{0}".format(area))

