2016-09-30 81 views
0

這是一個問題,我的任務在編程的介紹和我不完全理解如何做到這一點,而不使用Ifs因爲我們的教授只是想要基本模數和分裂。我試圖得到3個輸出。氣球大於兒童(工作),氣球等於只輸出0和0的兒童,氣球比兒童小,這不起作用。Python 2.7計算餘數與除法和兩個輸入

# number of balloons 
children = int(input("Enter number of balloons: ")) 

# number of children coming to the party 
balloons = int(input("Enter the number of children coming to the party: ")) 

# number of balloons each child will receive 
receive_balloons = int(balloons % children) 

# number of balloons leftover for decorations 
remaining = children % balloons 

print("{:s}""{:d}""{:s}""{:d}".format("Number of balloons for each child is ", receive_balloons, " and the amount leftover is ", remaining)) 

print(balloons, "", (remaining)) 
+0

你覺得呢''%呢?你的這兩個用法都不正確。 – user2357112

+0

它是不是將它分開並計算餘數? – roysizzle

+0

它的確如此,所以你的問題可能與數學有關。你爲什麼認爲將氣球數量除以兒童數量的餘數*是每個孩子接收到的氣球數量?你爲什麼要將*孩子的數量除以*氣球的數量*,並將其餘部分用於找出剩餘氣球的數量? – user2357112

回答

1

你需要修復您的變量賦值,你是分配給了錯誤的變量,實際上劃分數正確獲取receive_balloons

balloons = int(input("Enter number of balloons: ")) 
children = int(input("Enter the number of children coming to the party: ")) 

receive_balloons = balloons // children 
remaining = balloons % children 

# Alternatively 
receive_balloons, remaining = divmod(balloons, children) 

print("Number of balloons for each child is {} and the amount leftover is {}".format(receive_balloons, remaining)) 

輸出(10/5):

Enter number of balloons: 10 
Enter the number of children coming to the party: 5 
Number of balloons for each child is 2 and the amount leftover is 0 

輸出(10/8):

Enter number of balloons: 10 
Enter the number of children coming to the party: 8 
Number of balloons for each child is 1 and the amount leftover is 2 

注意:在Python2.7中,您應該使用raw_input

+0

所以我已經切換變量的正確順序,現在接收氣球只輸出0,這是我以前輸入的兒童數量:10 輸入氣球的數量:5 每個孩子的氣球數量爲0剩餘金額爲5 – roysizzle

+0

抱歉無法複製您的問題......請參閱上面的輸出。 – AChampion

+0

如果我利用raw_input,我得到一個未定義的變量 – roysizzle

1

你需要使用//運營商爲每名兒童和氣球%的數量剩餘的氣球

# number of balloons 
balloons = int(input("Enter number of balloons: ")) 

# number of children coming to the party 
children = int(input("Enter the number of children coming to the party: ")) 

receive_balloons, remaining = (balloons // children, balloons % children) 

print("{:s}""{:d}""{:s}""{:d}".format("Number of balloons for each child is ", receive_balloons, " and the amount leftover is ", remaining)) 

print(balloons, "", (remaining)) 
+0

這個工程,但如果可能的話,我可以解釋你的receive_balloons 剩餘=(氣球//兒童,氣球%兒童)? 我不知道你可以做一個雙重計算 – roysizzle

+0

你可以在賦值時解開一個「元組」,例如: 'a,b =(1,2)'是相同的'a = 1'和'b = 2',上面的代碼創建了來自除法和模數的值的「元組」並將它們賦值給變量。語法糖。 – AChampion

+0

在這個例子中,作業也是解開一個元組的包裝。元組是括號中的位。元組的每個元素被單獨分配給一個變量。 –