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.(打印出结果)


分析以上思路(伪代码),可以得出:

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)

本文有@易枭寒(499065469@qq.com)根据MIT公开课整理。转载请注明出处和作者信息。





  • 0
    点赞
  • 3
    收藏
    觉得还不错? 一键收藏
  • 1
    评论
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值