用python实现“已知三角形两个直角边,求斜边”
要求:用户输入两个直角边(数值为浮点类型),若非浮点类型,则提示用户,继续输入。
思路:伪代码描述下步骤
1、-input a value for the base as a float(输入某浮点数作为底边值)
立即学习“Python免费学习笔记(深入)”;
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-8import math# 取底inputOK = Falsewhile not inputOK: base = input('输入底:') if type(base) == type(1.0): inputOK = True else: print('错误,底必须为浮点数') # 取高inputOK = Falsewhile 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求第三条边边长的详细内容,更多请关注【创想鸟】其它相关文章!
版权声明:本文内容由互联网用户自发贡献,该文观点仅代表作者本人。本站仅提供信息存储空间服务,不拥有所有权,不承担相关法律责任。如发现本站有涉嫌抄袭侵权/违法违规的内容, 请发送邮件至253000106@qq.com举报,一经查实,本站将立刻删除。
发布者:PHP中文网,转转请注明出处:https://www.chuangxiangniao.com/p/2256916.html