2016-09-30 2 views
0

プログラミングのイントロでの私の割り当てには問題があります。私たちの教授は基本的なモジュラスと除算がほしいから、Ifを使用しないとこれを行う方法をあまり理解できません。私は3つの出力を取得しようとしています。 (動作する)子供よりも大きい風船、0と0を出力する子供に等しい風船、子供の風船よりも小さい風船、それは働きません。Python 2.7除算と2つの入力で剰余を計算する

あなたの変数の割り当てを修正する必要が
# 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

割り当てに 'tuple'をアンパックすることができます。 'a、b =(1,2)'は 'a = 1'と' b = 2'と同じですが、上記コードは除算とモジュラスからの値のタプルを作成し、それらを変数に代入します。 Syntactic sugar。 – AChampion

+0

この例では、割り当てはタプルもアンパックしています。タプルは括弧内のビットです。タプルの各要素は、変数に個別に割り当てられます。 –

関連する問題