[英]How to find the maximum and minimum of integers without using a list or infinity?
So this is for an assignment where we're supposed to write code that asks a user for a number of integers, they input that number, then it asks them to, one at a time, put those numbers in. It then is supposed to find the maximum and minimum of those numbers and give them back to the user.所以这是一个作业,我们应该编写代码,要求用户输入一些整数,他们输入那个数字,然后它要求他们,一次一个,把这些数字放进去。然后应该是找到这些数字的最大值和最小值并将它们返回给用户。 We're at a point in the program where we can't use infinity or lists as well.我们正处于程序中无法同时使用无穷大或列表的位置。 I managed to do the first half, but I can't understand how to separate the numbers to compare them and find the values.我设法完成了前半部分,但我不明白如何将数字分开以比较它们并找到值。 I know what's not working now has something to do with the loop, but I'm not sure where to go. I'm a beginner, so literally any help is appreciated.我知道现在不工作与循环有关,但我不确定 go 的位置。我是初学者,所以从字面上看,任何帮助都会受到赞赏。
Also for clarification, we're using Python.另外为了澄清起见,我们使用的是 Python。
int_num = int(input("How many integers would you like to enter? "))
total = 0
print("Please enter", int_num, "integers.")
for num in range(1, int_num + 1):
integers = int(input())
if integers < min:
min_value = min
elif integers > max:
max_value = max
print("min:", min_value)
print("max:", max_value)
So another way is that you can assume the first inserted number is your minimum/maximum value.所以另一种方法是,您可以假设第一个插入的数字是您的最小值/最大值。 Then iterate through the rest(n-1) integers:然后遍历其余(n-1)个整数:
int_num = int(input("How many integers would you like to enter? "))
print("Please enter", int_num, "integers.")
min_value = max_value = int(input())
for _ in range(int_num - 1):
n = int(input())
if n < min_value:
min_value = n
elif n > max_value:
max_value = n
print("min:", min_value)
print("max:", max_value)
Note-1 : Don't use the built-in names as your variable name.注意 1 :不要使用内置名称作为变量名。 ( min
and max
) ( min
和max
)
Note-2 : There is no point for having range(1, int_num + 1)
Because you don't even use the loop variable.注 2 : range(1, int_num + 1)
没有意义,因为您甚至不使用循环变量。
Note-3 : You're not gonna calculate the total
of the numbers, so delete that extra variable.注 3 :你不会计算数字的total
,所以删除那个额外的变量。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.