程序基本结构和简单分支

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

例如:输入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()    
  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值