简体   繁体   English

Python:正多边形的面积

[英]Python: area of a regular polygon

I'm trying to calculate the area of a "regular polygon" (a regular polygon means that all sides of the polygon are the same). 我正在尝试计算“规则多边形”的面积(规则多边形表示多边形的所有边都相同)。 I created a method to do it, however, it seems to be off by "1" and I can't seem to figure out why. 我创建了一个方法来执行此操作,但是它似乎被“ 1”关闭了,我似乎无法弄清原因。

import math

if __name__=="__main__":

    num_sides = int(input("Enter the number of sides: "))
    side_length = float(input("Enter the side: "))

    def polygon_area(n_sides, length):
        area = (n_sides * (length ** 2)) / (4 * math.tan((math.pi) / n_sides))
        print(area)

    polygon_area(num_sides, side_length)

here is the formula I'm using to find the area of a regular polygon given 1 side 这是我用来查找给定1边的正多边形的面积的公式 在此处输入图片说明

here is the expected output that i am supposed to get 这是我应该得到的预期输出

在此处输入图片说明

So the expected result is supposed to be 73 .69017017488385, but I get 72 .69017017488385. 因此,预期结果应为73 .69017017488385,但我得到72 .69017017488385。 I thought it could be the order of operations or how the user input was being handled but they seem ok. 我认为这可能是操作的顺序,也可能是用户输入的处理方式,但似乎还可以。 I'm not sure at this point why it's off by 1. 我现在还不确定为什么会以1。

This is a well-known error in Liang's book. 在梁的书中,这是一个众所周知的错误。 The right answer is 72.69017017488385 . 正确的答案是72.69017017488385 As a side note, do not print() values in a function. 注意,请勿在函数中print()值。 return them and let the caller do the printing. return给他们,让呼叫者进行打印。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM