您的位置:首页 > 其它

程序基本结构和简单分支

2017-09-03 18:08 141 查看


任何算法(程序)都可以用顺序、选择、循环这三种结构来实现程序框图。



例如:输入PM2.5来判断空气质量

如果值大于75,输出空气污染警告,如果小于75,输出空气良好。

# pm25.py
# 空气质量提醒

def main():
PM=eval(input("What is today's PM2.5?"))
#打印相应提醒
if PM>75:
print("Unhealthy. Be careful!")
else:
print("Good. Go running!")
main()


求解二次方的实数根

# 二次方的实数根程序
# 此程序在方程没有实根的情况下报错
import math
def main():
print("This program finds the real solutions to a quadratic\n")
a,b,c=eval(input("please enter the coefficients(a,b,c)"))
discRoot=math.sqrt(b*b-4*a*c)
root1=(-b+discRoot)/(2*a)
root2=(-b-discRoot)/(2*a)
print("\nThe solutions are :",root1,root2)
main()


输入输出

This program finds the real solutions to a quadratic

please enter the coefficients(a,b,c)(1,2,1)

The solutions are : -1.0 -1.0
>>>


上面程序是不完美的,因为没有实根的情况下是错误的,所以改进后需要判断语句来判断
delta=b*b-4*a*c
是否大于等于0或者小于0,然后输出提示。

修改后代码如下

# 二次方的实数根程序
# 此程序在方程没有实根的情况下报错
import math
def main():
print("This program finds the real solutions to a quadratic\n")
a,b,c=eval(input("please enter the coefficients(a,b,c)"))
delta=b*b-4*a*c
if delta<0:
print("\nThe quation has no real roots!")
else:
discRoot=math.sqrt(delta)
root1=(-b+discRoot)/(2*a)
root2=(-b-discRoot)/(2*a)
print("\nThe solutions are :",root1,root2)
main()
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: