我的if语句究竟出了什么问题?

gos*_*tag 2 c++

我尝试了不同的方法来布置我的if语句,我甚至试过嵌套的if语句.我得到了相同的结果.除了显示我的代码之外,我不确定是否有任何方式可以提出我的问题.

#include <iostream>
#include <conio.h>
#include <string>

using namespace std;

int main()
{
char playerOne, playerTwo;

cout<<"ROCK PAPER SCISSORS!"<<endl;
cout<<"Enter P for Paper"<<endl;
cout<<"Enter R for Rock"<<endl;
cout<<"Enter S for Scissors"<<endl;

cout<<"Player One enter your choice: ";
cin>>playerOne;

cout<<"Player Two enter your choice: ";
cin>>playerTwo;

if ((playerOne = 'R') && (playerTwo = 'R'))
    cout<<"Both players played same hand";
else if ((playerOne = 'R') && (playerTwo = 'P'))
    cout<<"Player Two wins!";
else if ((playerOne = 'R') && (playerTwo = 'S'))
    cout<<"Player One wins!";
else if ((playerOne = 'P') && (playerTwo = 'R'))
    cout<<"Player One wins!";
else if ((playerOne = 'P') && (playerTwo = 'P'))
    cout<<"Both players played same hand";
else if ((playerOne = 'P') && (playerTwo = 'S'))
    cout<<"Player Two wins!";
else if ((playerOne = 'S') && (playerTwo = 'R'))
    cout<<"Player Two wins!";
else if ((playerOne = 'S') && (playerTwo = 'P'))
    cout<<"Player One wins!";
else if ((playerOne = 'S') && (playerTwo = 'S'))
    cout<<"Both players played same hand";
else
    cout<<"Invalid inputs!";

getche();
return 0;
}
Run Code Online (Sandbox Code Playgroud)

ajo*_*jon 12

你需要双==号而不是=

== 可以理解为"等于"


Leo*_*eon 6

你必须使用==而不是=.==相等和运算符的运算符测试=是赋值运算符

通过使用=您分配而不是测试相等性.因此,当赋值成功时,条件总是求值为真,除非赋值是(或有效)为0.(感谢pickypg)

  • 你应该澄清的一点:`variable ="blah";`返回true取决于我相信左手的设置(至少在php和javascript中),而不仅仅是因为它会成功 (2认同)