2017-02-10 93 views
1

这只是一个介绍性的类代码,我想知道如何找到所有next_value变量的最大值并将其与first_value进行比较以打印最大值。我的if语句是接近,但我不知道如何解决它查找循环中的最大值

maximum = 0.0 
value = int(input("Enter the number of values to process: ")) 

first_value = float(input("First value: ")) 
next_value_total = 0 


for i in range(1, value): 
    next_value = float(input("Next value: ")) 
    next_value_total += next_value 
    if first_value <= next_value: 
     maximum = next_value 
    elif first_value > next_value: 
     maximum = first_value 

total = next_value_total + first_value 
print("The total is {:.1f}".format(total)) 
print("The maximum is {:.1f}".format(maximum)) 
+0

那么,有什么问题呢? –

+0

它并不总是正确打印最大值 –

回答

1

我会尽量保持我的回答十分简洁越好:

value = int(input("Enter the number of values to process: ")) 

first_value = float(input("First value: ")) 

total = first_value 
maximum = first_value 

for i in range(1, value): 
    next_value = float(input("Next value: ")) 
    total += next_value 
    if maximum <= next_value: 
     maximum = next_value 

print("The total is {:.1f}".format(total)) 
print("The maximum is {:.1f}".format(maximum)) 
+0

谢谢,我刚添加了另一个if语句,将它与first_value进行比较以找到真正的最大值,我认为它可以工作 –

+0

如果输入您建议的数字:要处理的值数:5,第一个值:100,下一个值:90,下一个值:105,下一个值:80,下一个值:102,我的代码打印:合计为477.0,最大为105.0(这是正确的) – caspillaga

0

我只想把该值一个列表,并获得之和最大后,像这样:

value = int(input("Enter the number of values to process: ")) 
values = [] 

for i in range(value): 
    next_value = float(input("Next value: ")) 
    values.append(next_value) 

print("The total is {:.1f}".format(sum(values))) 
print("The maximum is {:.1f}".format(max(values))) 

但是,如果你想保持相同的结构:

maximum = 0.0 
value = int(input("Enter the number of values to process: ")) 

first_value = float(input("First value: ")) 
next_value_total = 0 
maximum = first_value # Note: initialize the maximum here 

for i in range(1, value): 
    next_value = float(input("Next value: ")) 
    next_value_total += next_value 
    if next_value > maximum: 
     maximum = next_value 

total = next_value_total + first_value 
print("The total is {:.1f}".format(total)) 
print("The maximum is {:.1f}".format(maximum)) 

您也可以用maximum = max(maximum, next_value)代替if next_value > maximum: maximum = next_value

+0

谢谢我们还没有在课程中学习清单,感谢您的帮助! –

0

如果你使用一个列表,而不是你可以分别使用sum()max()

num_values = int(input("Enter the number of values to process: ")) 

values = [] 
for i in range(1, num_values + 1): 
    value = float(input("Please enter value %d: " % i)) 
    values.append(value) 

print("The total is {:.1f}".format(sum(values))) 
print("The maximum is {:.1f}".format(max(values))) 

实例应用:

Enter the number of values to process: 3 
Please enter value 1: 4.0 
Please enter value 2: 5.6 
Please enter value 3: 7.2324234 
The total is 16.8 
The maximum is 7.2 

试试吧here!

+0

谢谢,我们还没有在课程中学到名单,感谢您的帮助! –