用python输入任意三条边长_如何用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输入任意三条边长_如何用python求第三条边边长的全部內容,希望文章能夠幫你解決所遇到的問題。
- 上一篇: ue4 无限地图_UE4大地图(流关卡、
- 下一篇: 跌跌不休的特斯拉何时能反转