首页
学习
活动
专区
圈层
工具
发布
社区首页 >问答首页 >如何仅使用If,elif语句解决一个基本的Richter标度问题

如何仅使用If,elif语句解决一个基本的Richter标度问题
EN

Stack Overflow用户
提问于 2020-10-23 10:54:12
回答 1查看 571关注 0票数 1

我是一个完全的初学者,但通过一个练习来编写一个程序来读取输入和显示描述符。

关于以下代码:

预期结果是"Meteoric"

  • Current结果是“非常小”的

我知道这是基本的,但要从某个地方开始。

我做错了什么?

代码语言:javascript
复制
mag = float(10)

# Determine the richter 

if mag < float(2.0):
    print("Micro")
elif mag >= float(2.0) < float(3.0):
    print("Very Minor")
elif mag >= float(3.0) < float(4.0):
    print("Minor")
elif mag >= float(4.0) < float(5.0):
    print("Light")
elif mag >= float(5.0) < float(6.0):
    print("Moderate")
elif mag >= float(6.0) < float(7.0):
    print("Strong")
elif mag >= float(7.0) < float(8.0):
    print("Major")
elif mag >= float(8.0) < float(10.0):
    print("Great")
elif mag >= float(10.0):
    print("Meteoric")
else:
    print("Error")
EN

回答 1

Stack Overflow用户

回答已采纳

发布于 2020-10-23 11:10:30

你把一些条件倒过来了。

我为解决这个问题所做的就是让代码更易读(对我自己来说),然后,就像魔法一样,错误消失了。

我的意思是,如果您能够快速阅读代码,这可能意味着您可以快速调试它,这意味着它有较少的bug。

  1. 只使用<<=,而不使用>>=,以便始终用眼睛而不是从逻辑中看到手边的条件--
  2. --无需将3.0等数字转换为浮动。

G 210

工作代码:

代码语言:javascript
复制
mag = float(10)

# Determine the richter

if mag < 2.0:
    print("Micro")
elif 2.0 <= mag < 3.0:
    print("Very Minor")
elif 3.0 <= mag < 4.0:
    print("Minor")
elif 4.0 <= mag < 5.0:
    print("Light")
elif 5.0 <= mag < 6.0:
    print("Moderate")
elif 6.0 <= mag < 7.0:
    print("Strong")
elif 7.0 <= mag < 8.0:
    print("Major")
elif 8.0 <= mag < 10.0:
    print("Great")
elif 10.0 <= mag:
    print("Meteoric")
else:
    print("Error")

问题是:

mag >= float(2.0) < float(3.0):这样的条件

翻译成

mag >= float(2.0) and float(2.0) < float(3.0):

这和

True and True:

那就是

True

你得到了Very Minor

票数 0
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/64498674

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档