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 = 5andlength = 7directly inside the function. This means no matter what values you pass when callingpolygon_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 oftan(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_areainstead of calling it with arguments (likepolygon_area(5, 7)). - The string formatting syntax is incomplete. You need to include a format specifier (like
%.2ffor a rounded float) to pair with the%operator, or use a modern f-string for cleaner code.
- You're referencing the function name
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
相关产品推荐
相关产品推荐

