2014-02-07 18 views
-1

編寫一個讀取三個整數並打印哪個值較大的程序。你的程序必須被命名爲biggest.py並且可以由主功能,然後在主函數cs類的python條件

這裏打電話的是我寫的:

def main(): 
    a = int(input("the first integer? ")) 
    b = int(input("the second integer? ")) 
    c = int(input("the third integer? ")) 
    if a > b > c: 
    print("the first integer is the largest") 
    elif b > a > c: 
    print("the second integer is the largest") 
    elif c > a > c:   
    print("the third integer is the largest") 
main() 

然而,當我運行的程序是要求輸入整數,但沒有給我任何結果後,我輸入整數

+1

第三個elif永遠不會被觸發。除非按遞減順序輸入整數或者輸入中,高,低,否則不會得到輸出。 – StephenTG

+2

3個數字有6種可能的排列組合。你確定3個條件足夠了嗎? – timrau

+0

嘗試在Python解釋器中運行代碼以確定邏輯中的錯誤。更重要的是,在嘗試編寫代碼之前,我會試着在紙上做這件事。 –

回答

3

你的條件是太嚴格,你想完成什麼。你應該用以下內容替換它們:

if (a > b and a > c): 
elif (b > a and b > c): 
elif (c > b and c > a): 
+0

如果'a == b'會怎麼樣? – timrau

+0

不知道你想做什麼,如果有一個最大的領帶。因爲我的方法不會產生任何輸出。 – StephenTG

+0

如果一個==最大(a,b,c)'? –

0

它可能會更容易地扔在一個列表中的值,並對其進行排序:如果您想處理平等條件

list_ = [a, b, c] 
list_.sort(reverse=True) 
print(list_[0]) 
+0

如果OP需要他提到的形式的輸出,他們仍然需要遵循這一點,以一些有條件的東西 – StephenTG

+2

'list_ = zip([a,b,c],['first','second','第三']); print'{}數字最大'.format(sorted(list_,reverse = True)[0] [1])' – roippi

1

,或者您想在任何條件下打印一個消息,你可以嘗試處理平等狀況在elif塊或打印消息中的else塊:

answer = "" 
if (a > b and a > c): 
    answer = "a is the biggest: %s" % a 
elif (b > a and b > c): 
    answer = "b is the biggest: %s" % b 
elif (c > b and c > a): 
    answer = "c is the biggest: %s" % c 
elif (a==b or a==c or b==c): 
    answer = "there is equality in some values" 

但如果你想要做的更好的方法,使用if塊和做檢查對於每個條件:

answer = [] 
if (a >= b and a >= c): 
    answer.append(a) 
if (b >= a and b >= c): 
    answer.append(b) 
if (c >= b and c >= a): 
    answer.append(c) 
# Your answer list now contains the biggest value, or biggest values if two or more input have the same value and are the biggest within all inputs. 
if len(answer) == 1: 
    print "biggest values is: %s" % answer[0] 
else: 
    print "more than one values are the highest ones: %s" % answer[0] 

使用if讓你檢查各種可能性,並使用>=,您可以處理平等的條件。