【问题标题】:i have thes exam and i dont know what is the problem in my answer我有这些考试,我不知道我的答案有什么问题
【发布时间】:2022-01-03 09:53:15
【问题描述】:

编写一个 Python 代码 sn-p 使用 'if-elif' 流控制和一个 'while' 循环:

  1. 指示用户输入大于 0 且小于或等于 10 的数字,并将输入作为浮点值存储在变量中
  2. 如果输入的数字大于0小于等于10,
  3. 使用“while”循环将数字与自身相加,直到总和超过 100。
  4. 总和超过 100 后,使用 print 语句输出总和
  5. 否则,输出消息“您没有输入介于 0 和 10 之间的值”

我的回答:

inval = float(input('Input a number greater than zero and less than or equal to 10: '))
if inval > 0 and inval <= 10:
    while inval < 100:
        inval += inval
        continue
    else:
        print(inval)
elif inval <= 0 or inval > 10:
    print('You did not enter a value between 0 and 10')

【问题讨论】:

  • 我的猜测:inval &lt; 100 应该是 inval &lt;= 100
  • 您遇到了什么问题?作为旁注,您不需要continueelse。删除那些并取消缩进print

标签: python python-3.x python-2.7 python-requests


【解决方案1】:

您的答案不被接受的原因是代码应该返回100.0 以获取6.25 之类的输入。但是,由于您的 while 条件,您的代码返回 200.0。您可以添加一个等号 (=) 来解决此问题。而且,我从您的代码中删除了不必要的部分。

inval = float(input('Input a number greater than zero and less than or equal to 10: '))
if inval > 0 and inval <= 10:
    while inval <= 100:
        inval += inval
    print(inval)
else:
    print('You did not enter a value between 0 and 10')

【讨论】:

  • 要求 3 表示总和“超过 100.0”,因此您的小于或等于条件不正确。
  • @PaulCornelius 你应该再考虑一下。
  • 呃!答案是对的。
【解决方案2】:

我认为唯一可能出错的是While循环的条件(你应该把它放在inval &lt;= 100)。 但是,问题可能出在循环内的 else 上;因为,它不是“有效的”,在 inval 值大于 100 之后,即使 else 不存在,它也会打印该值。 见:

inval = float(input('Input a number greater than zero and less than or equal to 10: '))
if inval > 0 and inval <= 10:
    while inval <= 100:
        inval += inval
    print(inval)

elif inval <= 0 or inval > 10:
    print('You did not enter a value between 0 and 10')

我在您的代码中没有看到其他问题 :)

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2023-02-21
    • 2020-11-21
    • 2021-09-04
    • 2015-09-11
    • 1970-01-01
    相关资源
    最近更新 更多