2017-02-10 92 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

謝謝,我們還沒有在課程中學到名單,感謝您的幫助! –