gpt4 book ai didi

c++ - “Rock, paper, scissors” C++代码有问题

转载 作者:行者123 更新时间:2023-12-01 14:44:14 26 4
gpt4 key购买 nike

我知道有多种方法可以为“岩石,纸张,剪刀”游戏编写代码。但是我已经根据我对C++的基本知识尝试编写以下代码。

using std::cin;
using std::cout;
using std::endl;
int main(int argc, char** argv) {
enum object {rock, paper, scissors}
object player1, player2;
cout <<"Enter two objetcs (objects include rock, paper or scissors):";
cin >>player1 >> player2;
if (player1==player2) cout <<"objects are equal";
else if (player1==rock && player2=paper cout << "player 2 is the winner";
else if (player1==rock && player2=scissors cout<<"player 1 is the winner";
else if (player1==paper && player2=rock) cout << "player 1 is the winner";
else if (player1==paper && player2=scissors) cout <<"Palyer 2 is the winnder";
else if (player1==scissors && player2=paper) cout << "Player 1 is winner";
else cout <<"Player 2 is the winner";
}

编译器 (Dev-C++)cin >>player1 >> player2;行中发现错误,解释了 "In Function 'int main(int, char**): [error] expected initializer before 'player1'"。我没有得到这个警告的意思。我如何在不对其结构进行太多更改的情况下改进此代码?

最佳答案

由于您的输入和枚举类型之间没有映射,因此实际上只能确定直接相等,否则最后的else语句将触发。下面,我用一种解决方案修改了您的代码,该解决方案接受char给出的cin值,然后用其枚举值设置对象。您还会有一些错字,缺少括号,分号和等号,因此请通读并注意差异。这不仅可以解决编译器错误,而且可以使您的代码按预期运行。

#include <iostream>

using std::cin;
using std::cout;
using std::endl;
int main(int argc, char** argv) {
enum object {rock, paper, scissors};
object player1, player2;
cout << "Enter two objetcs (objects include rock, paper or scissors):";
char p1, p2;
cin >> p1 >> p2;
if (p1 == 'r') {
player1 = rock;
}
else if (p1 == 'p') {
player1 = paper;
}
else if (p1 == 's') {
player1 = scissors;
}
else {
cout << "invalid input, play again" << endl;
exit(1);
}

if (p2 == 'r') {
player2 = rock;
}
else if (p2 == 'p') {
player2 = paper;
}
else if (p2 == 's') {
player2 = scissors;
}
else {
cout << "invalid input, play again" << endl;
exit(1);
}

if (player1==player2) cout <<"objects are equal";
else if (player1==rock && player2==paper) cout << "player 2 is the winner";
else if (player1==rock && player2==scissors) cout<<"player 1 is the winner";
else if (player1==paper && player2==rock) cout << "player 1 is the winner";
else if (player1==paper && player2==scissors) cout <<"Palyer 2 is the winnder";
else if (player1==scissors && player2==paper) cout << "Player 1 is winner";
else cout <<"Player 2 is the winner";
cout << endl;
}

了解类型以及在原始代码中如何确定输入对应于对象枚举的方式非常重要。

关于c++ - “Rock, paper, scissors” C++代码有问题,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58735618/

26 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com