如何用python求第三条边边长


本文摘自php中文网,作者爱喝马黛茶的安东尼,侵删。

用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、流程控制

代码一

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

20

21

22

23

#! /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)

分析代码一,会发现取底,取高的代码非常相似,这就会让人想到抽象成方法,实现模块化。

代码二

1

2

3

4

5

6

7

8

9

10

11

12

13

14

15

16

17

18

19

#!/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抽象类有什么用

Python中使用什么代替switch语句

详解Python中实现延时回调普通函数

Python实现在idle中输入多行的方法

Python怎么保留一位小数输出

Python什么意思中文

Python标准数据类型有哪些

解决pycharm找不到解释器的问题

Python中自定义函数的保留字是

怎么查看一个对象的类型

更多相关阅读请进入《Python》频道 >>




打赏

取消

感谢您的支持,我会继续努力的!

扫码支持
扫码打赏,您说多少就多少

打开支付宝扫一扫,即可进行扫码打赏哦

分享从这里开始,精彩与您同在

评论

管理员已关闭评论功能...