【问题标题】:Hello to everyone! I need a guide in this problem [closed]大家好!我需要这个问题的指南[关闭]
【发布时间】:2022-10-21 21:13:08
【问题描述】:

创建一个程序,它将接受一个正整数和负整数并将其存储在一个列表中,直到用户输入 /。显示所有输入的总和和平均值以及可以找到的最高和最低值和索引号。 Python 编程 这是我正在关注的示例:

Sample input/output:

Enter No. 1: 45
Enter No. 2: 89
Enter No. 3: 35
Enter No. 4: 90
Enter No. 5: 88
Enter No. 6: /

The sum of all inputs is 347
The average of all inputs is 69.40
The highest input is 90 found at the index 3
The lowest input is 35 found at the index 2 

底部是我使用while循环的代码。我需要知道是什么问题。 我正在使用python编程语言。

from statistics import mean
ows=[]
ct=1

while True:
    num=input("Enter No." + str(ct) + ": ")
    ct+=1
    if num=="/":
        break
    num=int(num)
    ows.append(num)
av = sum(ows)/len(ows)
    
print("THe sum of all inputs is", sum(ows))
print("The average of all inputs is", "%.2f"%av)
print("The highest input is",max(ows),f"found at the index")
print("The lowest input is",min(ows),f"found at the index")

【问题讨论】:

  • 您缺少 max 和 min 的索引,您可以使用 argmaxargmin 来实现
  • 那么你可以发送一个例子或图片吗?所以我可以看到我错过了什么?
  • 你自己做代码吗?或者你只是从别人那里拿了代码?
  • 我的评论给你一个关于如何解决它的提示。但是想要已经为您编码的解决方案让我怀疑您可能没有编写其余代码。
  • (如果问题是“我怎样才能找到最低和最高数字的索引?”,f / e,这比“不工作”更可行)

标签: python while-loop


【解决方案1】:

您可以使用.index() 从列表中获取特定元素的索引,将其与min()max() 结合使用以查找它们在ows 列表中的位置。

from statistics import mean
ows = []
ct = 1

while True:
    num=input("Enter No." + str(ct) + ": ")
    ct + =1
    if num == "/":
        break
    num = int(num)
    ows.append(num)
av = sum(ows) / len(ows)
    
print("THe sum of all inputs is", sum(ows))
print("The average of all inputs is", "%.2f"%av)
print("The highest input is",max(ows),f"found at the index", ows.index(max(ows)))
print("The lowest input is",min(ows),f"found at the index", ows.index(min(ows)))

您可以进行的另一项改进是删除ct 变量以跟踪接下来输入的数字;相反,您可以使用len(ows) 获取列表中总数的长度,然后加 1 以计算即将输入的下一个数字:

num = input("Enter No." + str(len(ows) + 1) + ": ")

【讨论】:

    【解决方案2】:

    这是一个工作版本

    numbers = []
    while True:
        number = input("Enter a number: ")
        if number == "/":
            break
        number = int(number)
        numbers.append(number)  
    print(f"The sum of all inputs is: {sum(numbers)}")
    print(f"The average of all inputs is: {sum(numbers)/len(numbers)}")
    print(f"The highest input is: {max(numbers)} found at the index: {numbers.index(max(numbers))}")
    print(f"The lowest input is: {min(numbers)} found at the index: {numbers.index(min(numbers))}")
    

    输入

    > Enter a number: 1
    > Enter a number: 2
    > Enter a number: 3
    > Enter a number: /
    

    输出

    所有输入的总和为:6

    所有输入的平均值为:2.0

    最高输入是:3 在索引处找到:2

    最低输入是:1 在索引处找到:0

    【讨论】:

      猜你喜欢
      • 2022-08-19
      • 1970-01-01
      • 1970-01-01
      • 2020-01-03
      • 2012-03-28
      • 1970-01-01
      • 2022-11-02
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多