用Python编写一个程序,从用户读取整数输入(数据)序列,然后输出以下结果:
所有输入的总数,最小的输入,最大的输入,偶数输入的数目,奇数输入的数目,所有输入的平均值。
您不知道用户需要输入多少个数字,所以每次您都必须询问她是否有其他数字要添加到序列中。
到目前为止,这是我的代码,但是我想知道是否有一种不用sys模块的方法
import sys
# declare a variable largest which has smallest integer value
# -sys.maxsize gives the smallest integer value,you can also use any smallest value
largest = -sys.maxsize
# declare a variable smallest, that is assigned with maximum integer value
smallest = sys.maxsize
# declare variables total to store the sum of all numbers
total = 0
# option variable is to store the user option Y or N
option = 'y'
# declare variables to count odd, even and totalCount
evenCount = 0
oddCount = 0
totalCount = 0
print("This program will calculate statistics for your integer data.")
# run the loop when the user enters y or Y
while option == 'y' or option == 'Y':
# take input of number
number = int(input("Please type a number: "))
# add the number to total
total = total + number
# increase totalCount
totalCount = totalCount + 1
# calculate smallest
if number < smallest:
smallest = number
# calculate largest
if number > largest:
largest = number
# calculate count of even and odd numbers
if number % 2 == 0:
evenCount = evenCount + 1
else:
oddCount = oddCount + 1
option = input("Do you have another number to enter? ")
# calculate average
average = total / totalCount
# print the output
print("\nThe total of your numbers is:", total)
print("The smallest of your numbers is:", smallest)
print("The largest nof yout numbers is:", largest)
print("The number of even numbers is:", evenCount)
print("The number of odd numbers is:", oddCount)
print("The average of your numbers is:", average)发布于 2022-10-24 03:47:01
答案是“能做得到吗?”在编程方面,几乎总是“是的”。
在这种情况下,您可以测试是否处于第一个循环迭代,并相应地设置smallest和largest。
例如。
option = 'y'
first_loop = True
while option.lower() == 'y':
x = int(input("Please type a number: "))
if first_loop:
smallest = x
first_loop = False
elif x < smallest:
smallest = x
option = input("Do you have another number to enter? ")
print(f"Smallest number entered is {smallest}")您还可以将输入数字收集到列表中。
option = 'y'
inputs = []
while option.lower() == 'y':
x = int(input("Please type a number: "))
inputs.append(x)
option = input("Do you have another number to enter? ")现在,如果您有inputs中的所有输入数字,那么计算最小值和最大值的值就是min(inputs)和max(inputs)。
发布于 2022-10-24 03:46:57
有趣的方法,当我遇到这样的问题时,我会使用float('inf')或float('-inf')。可以很容易地运用到你的方法中。
https://stackoverflow.com/questions/74176488
复制相似问题