0

所以我写这个程序是一个两人玩剪刀石头布的游戏,无论每个玩家选择什么,输出都是“玩家 1 获胜”。

#include <stdio.h>
int main(void)
{
long player1Choice, player2Choice, p, r, s;


        printf("Player 1, enter paper (p), rock (r), or scissors (s)\n");
            player1Choice=getchar();
            getchar();

        printf("Player 2, enter paper (p), rock (r), or scissors (s)\n");
            player2Choice=getchar();
            getchar();

        if((player1Choice=p)&&(player2Choice=r))    
            printf("Player 1 wins!\n");
        else if((player1Choice=r)&&(player2Choice=p))
            printf("Player 2 wins!\n");
        else if((player1Choice=r)&&(player2Choice=s))
            printf("Player 1 wins!\n");
        else if((player1Choice=s)&&(player2Choice=r))
            printf("Player 2 wins!\n");
        else if((player1Choice=s)&&(player2Choice=p))
            printf("PLayer 1 wins!\n");
        else if((player1Choice=p)&&(player2Choice=s))
            printf("Player 2 wins!\n");


    printf("Press any key to exit");
    getchar();
    return 0;
}

我认为我的“if”语句中的逻辑“and”可能会造成麻烦,但我不确定。

4

2 回答 2

2

您在字符常量周围缺少单引号,并且=在需要时也使用==. 所以改变例如

    if((player1Choice=p)&&(player2Choice=r))    

至:

    if((player1Choice=='p')&&(player2Choice=='r'))    

对所有类似事件执行此操作。

还要去掉未使用的变量rps

最后,打开编译器警告并注意它们- 如果您允许,编译器会帮助您解决所有这些问题。

于 2013-10-03T21:36:13.507 回答
1

您已声明prs,但从未初始化它们。您还使用了赋值 ( =) 而不是相等性测试 ( ==)。您的程序会导致未定义的行为。看起来您的意图是:

if ((player1Choice == 'p') && (player2Choice == 'r'))

修复这些后,您可以摆脱虚假变量。或者,更改您的变量声明以包括初始化:

long player1Choice, player2Choice, p = 'p', r = 'r', s = 's';

你仍然需要解决你的=问题。

您应该在编译器中打开更多警告。例如,对于您的程序,来自 Clang:

$ clang -Wall example.c -o example
example.c:19:51: warning: variable 's' is uninitialized when used here
      [-Wuninitialized]
        else if((player1Choice=r)&&(player2Choice=s))
                                                  ^
example.c:4:43: note: initialize the variable 's' to silence this warning
long player1Choice, player2Choice, p, r, s;
                                          ^
                                           = 0
example.c:15:27: warning: variable 'p' is uninitialized when used here
      [-Wuninitialized]
        if((player1Choice=p)&&(player2Choice=r))    
                          ^
example.c:4:37: note: initialize the variable 'p' to silence this warning
long player1Choice, player2Choice, p, r, s;
                                    ^
                                     = 0
example.c:15:46: warning: variable 'r' is uninitialized when used here
      [-Wuninitialized]
        if((player1Choice=p)&&(player2Choice=r))    
                                             ^
example.c:4:40: note: initialize the variable 'r' to silence this warning
long player1Choice, player2Choice, p, r, s;
                                       ^
                                        = 0
3 warnings generated.
于 2013-10-03T21:36:15.277 回答