You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

Python正则多边形面积计算程序print语句崩溃求助

Fixing Your Regular Polygon Area Calculator

Let's walk through the bugs in your code step by step to get it running without crashes:

  • Hardcoded parameters overriding inputs: You've set sides = 5 and length = 7 directly inside the function. This means no matter what values you pass when calling polygon_area(), they'll get overwritten immediately. Delete those two lines to let the function use the arguments you provide.

  • Syntax & math error in the return statement:

    • Your expression is missing a closing parenthesis at the end, which causes a syntax crash.
    • The trigonometric calculation is wrong: it should be tan(pi / sides) instead of tan(pi)/sides. tan(pi) equals 0, so your original code would try to divide by 0 (a huge red flag!)—the correct formula uses the tangent of π divided by the number of sides.
  • Broken print statement:

    • You're referencing the function name polygon_area instead of calling it with arguments (like polygon_area(5, 7)).
    • The string formatting syntax is incomplete. You need to include a format specifier (like %.2f for a rounded float) to pair with the % operator, or use a modern f-string for cleaner code.

Corrected Code

from math import tan, pi

def polygon_area(sides, length):
    """Returns the area of a regular polygon."""
    # Use the passed-in parameters instead of hardcoding
    return (sides * (length ** 2)) / (4 * tan(pi / sides))

# Example call with proper formatting
print("The area of the polygon is %.2f" % polygon_area(5, 7))
# Alternatively, using f-strings (Python 3.6+):
# print(f"The area of the polygon is {polygon_area(5, 7):.2f}")

When you run this, it'll correctly calculate the area of a 5-sided polygon with side length 7 and print the result without crashing.

内容的提问来源于stack exchange,提问作者MarthaV

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.20 11:42:27