程序基本结构和简单分支

来源:互联网 发布:道亨软件多少钱 编辑:程序博客网 时间:2024/05/20 10:14

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

例如:输入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 mathdef 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 quadraticplease 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 mathdef 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()    
原创粉丝点击