本网站上的第一个问题,希望我以可接受的方式发布代码。我正在努力使这个摇滚,纸张,剪刀游戏工作,但我很难通过“你已进入线路”,因为它在此之后终止。
我的教授说我的问题是当randNumGenerated的类型为int时,userChoice的类型为char。我尝试使用以下代码转换我的r,p和s值: char r ='a'; int a = r;
但是编译器得到了“重新定义:不同的基本类型”错误。我不知道该怎么做,因为将变量重新定义为int是我的意图。我觉得这一切都错了吗?任何帮助将不胜感激!
int main()
{
char userChoice;
int computer;
int randNumGenerated = 0;
int r = 0;
int p = 0;
int s = 0;
unsigned seed;
cout << "Chose either rock, paper, or scissors" << endl;
cout << "Let r,p,and s represent rock,paper,and scissors respectively " << endl;
cin >> userChoice;
cout << "You entered: " << userChoice << endl;
cout << " " << endl;
seed = time(0);
srand(seed);
randNumGenerated = rand() % 3;
r == 0;
p == 1;
s == 2;
if ((userChoice == 0 && randNumGenerated == 2) || (userChoice == 1 && randNumGenerated == 0) || (userChoice == 2 && randNumGenerated == 1))
{
cout << "You win!";
}
if ((userChoice == 0 && randNumGenerated == 1) || (userChoice == 1 && randNumGenerated == 2) || (userChoice == 2 && randNumGenerated == 0))
{
cout << "You lose!";
}
if ((userChoice == 0 && randNumGenerated == 0) || (userChoice == 1 && randNumGenerated == 1) || (userChoice == 2 && randNumGenerated == 2))
{
cout << "It's a draw!";
}
return 0;
}
答案 0 :(得分:5)
这三行没有效果(字面意思,编译器应该警告你):
r == 0;
p == 1;
s == 2;
你可能正在寻找类似的东西:
int userNum = -1;
switch (userChoice) {
case 'r':
userNum = 0;
break;
case 'p':
userNum = 1;
break;
case 's':
userNum = 2;
break;
}
但是,为什么你甚至根本不使用整数?如果您使用了字符表示,那么您的if语句将更容易阅读:
char randomChosen = "rps"[randNumGenerated];
if ((userChoice == 'r' && randomChosen == 's') || ...) {
std::cout >> "You win!\n";
}
只要看一下这个,就能看出它是Rock vs Scissor。在基于数字的代码中,我必须回顾转换表。