如何用python求第三条边边长

爱喝马黛茶的安东尼
爱喝马黛茶的安东尼 原创
2019-06-19 16:52:01 7354浏览

用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核实处理。