欢迎访问 生活随笔!

生活随笔

当前位置: 首页 > 编程语言 > python >内容正文

python

用python输入任意三条边长_如何用python求第三条边边长

发布时间:2023/12/15 python 63 豆豆
生活随笔 收集整理的这篇文章主要介绍了 用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求第三条边边长的全部内容,希望文章能够帮你解决所遇到的问题。

如果觉得生活随笔网站内容还不错,欢迎将生活随笔推荐给好友。