我将e1和e2部分的代码基于在询问calculate width of a rectangle given perimeter and area
时找到的google等式的两半。
此部分代码设置为较大部分的一部分,以可视形式显示计算的矩形而不是使用整数,但是当我测试时,它给出的答案是不正确的。
import math
print("Welcome to Rectangles! Please dont use decimals!")
area = int(input("What is the area? "))
perim = int(input("What is the perimeter? "))
e1 = int((perim / 4) + .25)
e2 = int(perim**2 - (16 * area))
e3 = int(math.sqrt(e2))
width = int(e1 * e3)
print(width)
答案 0 :(得分:2)
建议您更好地命名变量,以便我们了解您尝试计算的内容。
从Google公式中,您应该直接翻译它。
import math
def get_width(P, A):
_sqrt = math.sqrt(P**2 - 16*A)
width_plus = 0.25*(P + _sqrt)
width_minus = 0.25*(P - _sqrt)
return width_minus, width_plus
print(get_width(16, 12)) # (2.0, 6.0)
print(get_width(100, 40)) # (0.8132267551043526, 49.18677324489565)
由于int(0.8132267551043526) == 0
重要提示:您的计算不会检查
area <= (perim**2)/16
答案 1 :(得分:2)
这是固定代码:
import math
print("Welcome to Rectangles! Please dont use decimals!")
S = int(input("Area "))
P = int(input("Perim "))
b = (math.sqrt (P**2-16*S)+P) /4
a = P/2-b
print (a,b)
答案 2 :(得分:2)
如果你不需要专门使用这个等式,那就更容易暴力破解它。
import math
print("Welcome to Rectangles! Please dont use decimals!")
area = int(input("What is the area? "))
perim = int(input("What is the perimeter? "))
lengths = range(math.ceil(perim/4), perim/2)
for l in lengths:
if l*(perim/2 - l) == area:
print(l)
答案 3 :(得分:1)
import math
print("Welcome to Rectangles! Please dont use decimals!")
area = int(input("What is the area? "))
perim = int(input("What is the perimeter? "))
e1 = int((perim / 4) + .25)
e2 = abs(perim**2 - (16 * area))
e3 = math.sqrt(e2)
width = e1 * e3
print(width)