问题描述
#include <iostream>
using namespace std;
int main()
{
int P1;
int P2;
int P,R,S;
cout<<"This is a Jack n Poy game. \nPlease select R for Rock,P for Paper,and S for Scissors.";
cout<<"\nPlayer one: ";
cin>>P1;
cout<<"\nPlayer two choice: ";
cin>>P2;
{
if ((P1==R)&&(P2==R))
{
cout<<"\nInvalid Game";
}
else if ((P1==P)&&(P2==R))
{
cout<<"\nPaper Covers Rock";
}
else if ((P1==R)&&(P2==S))
{
cout<<"\nRock Breaks Scissors";
}
else if((P1==P)&&(P2==R))
{
cout<<"\nPaper Covers Rock";
}
else if((P1==P)&&(P2==P))
{
cout<<"\nInvalid Game";
}
else if((P1==S)&&(P2==P))
{
cout<<"\nScissors Cuts Paper";
}
else if((P1==R)&&(P2==S))
{
cout<<"\nRock Breaks Scissors";
}
else if((P1==S)&&(P2==P))
{
cout<<"\nScissors Cuts Paper";
}
else if((P1==S)&&(P2==S))
{
cout<<("\nInvalid Game");
}
else
{
cout<<("You have select an invalid selection.");
}
}
}
我是 C++ 新手,这就是我目前正在研究的内容,我不知道该怎么做 rn 我尝试将变量更改为字符和字符串,但它显示类似 no match for 'operator&&'(operand types are 'std::__cxx11::basic__st...
我已经花了大约 3 个小时尝试这样做,但我想不出解决方案,任何帮助将不胜感激。
解决方法
您正在与未初始化的值进行比较:
int P,R,S;
您上面的变量从未被初始化。
也许,只是也许,您会想要使用字符而不是整数:
char player1;
char player2;
//...
std::cout << "Enter move for player 1: ";
std::cin >> player1;
std::cin.ignore(10000,'\n'); // Ignore rest of line.
std::cout << "Enter move for player 2: ";
std::cin >> player2;
std::cin.ignore(10000,'\n'); // Ignore rest of line.
player1 = std::tolower(player1);
player2 = std::tolower(player2);
if (player1 == player2)
{
std::cout << "Same move,invalid game.\n";
}
else if ((player1 == 'r') && (player2 == 's'))
{
std::cout << "Player 1 wins,rock beats scissors.\n";
}
//...
恕我直言,你的问题是你没有初始化你在比较中使用的变量,而且你可能使用了错误的数据类型(整数而不是字符)。
编辑 1:
语句if ((P1 == R)
将变量P1
的contents 与变量R
的contents 进行比较。这可能不是你想到的。也许您正在考虑将变量 P1
的内容与 R
之类的字母进行比较。
您可以将代码更改为:if ((P1 == 'R') //...
单引号用于表示字母而不是变量名。