2017-09-16 132 views
1

如果询问calculate width of a rectangle given perimeter and area,我将e1和e2代码部分作为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) 

 

+2

你可以给一个输入和预期的输出 –

+0

@KalyanReddy伊夫更新了帖子,澄清了一点,但说ID输入100作为区域和40则返回0外围进入12的区域, 16的周长将返回32. –

+1

您将周长除以4 ...因此,4个相等的边是正方形。因此任何一方都是宽度。为什么'.25'确实为你做?为什么会有一个随机的'16'? –

回答

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 
+0

哇谢谢,我假设检查防止任何结果没有意义? –

+0

正确。你不能取一个负数的平方根 –

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) 
+0

你改变了什么? –

+0

@ cricket_007更新 – Serjik

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

如果你不这样做需要专门使用这个方程式,它只会暴力蛮横。

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)