首頁  >  文章  >  後端開發  >  如何用python求第三邊邊長

如何用python求第三邊邊長

爱喝马黛茶的安东尼
爱喝马黛茶的安东尼原創
2019-06-19 16:52:018115瀏覽

用Python實現「已知三角形兩個直角邊,求斜邊」

要求:用戶輸入兩個直角邊(數值為浮點類型),若非浮點類型,則提示用戶,繼續輸入。

如何用python求第三邊邊長

想法:偽代碼描述下步驟

1、-input a value for the base as a float(輸入某浮點數作為底邊值)

2、-input a value for the height as a float(輸入某浮點數作為高的值)

3、-square root-- b squared plus h squared(求平方和和開根號)

4、-save that as a float in hype,for hypotenuse(把結果存為hyp,表示斜邊)

# 5、-print something out,using the value in hyp.(打印出結果)

#相關推薦:《Python視頻教程

##分析以上思路(偽代碼),可以得出:


0、使用者的輸入結果是各種情況,要小心使用者的輸入

1、程式碼的抽象化(開方的計算用math模組的sqrt內建函數)

2、流程控制

程式碼一

#! /usr/bin/env python
# encoding:utf-8
import math
# 取底
inputOK = False
while not inputOK:
    base = input('输入底:')
    if type(base) == type(1.0): 
inputOK = True
    else: 
print('错误,底必须为浮点数')    
# 取高
inputOK = False
while not inputOK:
    height = input('输入高:')
    if type(height) == type(1.0): 
inputOK = True
    else: 
print('错误,高必须为浮点数')
 
#斜边
hyp = math.sqrt(base*base + height*height) 
print '底' + str(base) + ',高' + str(height) + ',斜边' + str(hyp)

分析程式碼一,會發現取底,取高的程式碼非常相似,這會讓人想到抽象成方法,實現模組化。

程式碼二

#!/usr/bin/env python
#coding:utf-8 
import math 
"""
用户输入两个直角边(数值为浮点类型),若非浮点类型,则提示用户,继续输入。
""" 
def getFloat(requestMsg, errorMsg):
    inputOK = False
    while not inputOK:
        val = input(requestMsg)
        if type(val) == type(1.0): 
inputOK = True
        else: 
print(errorMsg)
    return val 
base = getFloat('输入底:','错误,底必须为浮点数')
height = getFloat('输入高:','错误,高必须为浮点数') 
hyp = math.sqrt(base*base + height*height) 
print '底' + str(base) + ',高' + str(height) + ',斜边' + str(hyp)

以上是如何用python求第三邊邊長的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn