无论输入如何,输出都相同

时间:2013-10-03 21:33:25

标签: c

所以我写这个程序是一个双人游戏的纸质剪刀,无论每个玩家选择什么,输出都是“玩家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”陈述中的逻辑“和”可能会造成麻烦,但我不确定。

2 个答案:

答案 0 :(得分:2)

您在字符常量周围缺少单引号,并且在需要=时也使用==。所以改变就好了。

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

为:

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

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

还要删除未使用的变量rps

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

答案 1 :(得分: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.