2017-09-16 84 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) 
相關問題