2016-10-17 2 views
0

**単純なエヴェンスとオッズのゲームでモジュラスを使うのに問題があります。 **プレイヤー+ cpu = 3%2 = 1であっても、偶数か奇数かに関係なく、「奇妙に勝ちました」または「勝てます。あなたが勝つ。あなたは括弧を使用する必要がモジュラスの問題

import random 
even_odds = list(range(0,2)) 
play = random.choice(even_odds) 
def selection(): 

which = input('Select O for odds and E for even: ').lower() 

if which == 'o': 
    odds() 

elif which == 'e': 
    evens() 

def odds(): 
    even_odds 
    cpu = random.choice(even_odds) 

    print("YOU CHOSE ODD") 
    player = int(input("Choose a number between 0 and 2: ")) 
    print('cpu chose',cpu) 
    print("You're choice plus the cpu's choice equals",player + cpu) 
    print(" /n ...", player + cpu % 2) 
    if player + cpu % 2 != 0: 
     print('Odd you win\n') 
     selection() 
    else: 
     print('Even you lose!\n') 
     selection() 


def evens(): 
    even_odds 
    cpu = random.choice(even_odds) 

    print("YOU CHOSE EVEN") 
    player = int(input("Choose number between 0 and 2: ")) 
    print('cpu chose',cpu) 
    print("You're choice plus the cpu's choice equals",player + cpu) 
    if player + cpu % 2 == 0: 
     print('Even you win! \n') 
     selection() 
    else: 
     print('Odd you lose! \n') 
     selection() 

出力

**Select O for odds and E for even: o 
YOU CHOSE ODD 
Choose a number between 0 and 2: 2 
cpu chose 0 
You're choice plus the cpu's choice equals 2 
... 2 
Odd you win** 

答えて

2

if (player + cpu) % 2 != 0: 

あなたは簡単な例との違いを確認できます。

In [10]: 5 + 5 % 2 
Out[10]: 6 

In [11]: (5 + 5) % 2 
Out[11]: 0 

%が高いを持っていますが+より大きいので、モジュロが最初に実行され、次に結果に5が加算されます。

In [12]: 5 % 2 
Out[12]: 1 

In [13]: 5 % 2 + 5 
Out[13]: 6 
+1

あなたの例を数回見て、私は完全に感謝します。 – Defalt

1

モジュロcpu変数に適用されます。

(player + cpu) % 2を使用して合計に適用します。

>>> player = 2 
>>> cpu = 1 
>>> player + cpu % 2 
3 
>>> (player + cpu) % 2 
1 

%*/で評価し、それは、(前に算出)operations+に先行します。

関連する問題