我一直在为学校做一个项目,使用功能制作一个摇滚剪刀游戏。这是我到目前为止的代码,但该程序存在一些问题。这就是该计划现在正在返回的内容。
Rock, Paper, Scissors
~~~~~~~~~~~~~~~~~~~~~
Rock: 1
Paper: 2
Scissors: 3
2
You picked:
Computer picked:
Press any key to continue . . .
它没有显示任何字符串,我不太了解该语言以找出原因:(我很感激代码上的一些帮助/指针/修复。我没有使用std命名空间,因为指南我发现它可能导致了这个问题。
#include <cmath>
#include <iostream>
#include <string>
std::string GetComputerChoice(std::string ComputerChoice)
{
double Computer;
Computer = rand() % 3 + 1;
if (Computer == 1)
{
ComputerChoice == "rock";
return ComputerChoice;
}
else if (Computer == 2)
{
ComputerChoice == "paper";
return ComputerChoice;
}
else
{
ComputerChoice == "scissors";
return ComputerChoice;
}
}
std::string GetUserChoice(std::string UserChoice)
{
double User;
std::cin >> User;
if (User < 1 || User > 3)
{
std::cout << "Invalid entry ";
system("pause");
return 0;
}
else if (User = 1)
{
UserChoice == "rock";
return UserChoice;
}
else if (User = 2)
{
UserChoice == "paper";
return UserChoice;
}
else
{
UserChoice == "scissors";
return UserChoice;
}
}
std::string DetermineWinner( std::string UserChoice, std::string ComputerChoice, std::string Victory )
{
Victory == "Something Has Gone Wrong";
if (ComputerChoice == UserChoice)
{
Victory == "Tie!";
return Victory;
}
else if (UserChoice == "rock")
{
if (ComputerChoice == "paper")
{
Victory == "Paper beats rock! You lose!";
return Victory;
}
else
{
Victory == "Rock smashes scissors! You win!";
return Victory;
}
}
else if (UserChoice == "paper")
{
if (ComputerChoice == "rock")
{
Victory == "Paper beats rock! You win!";
return Victory;
}
else
{
Victory == "Scissors cut paper! You lose!";
return Victory;
}
}
else
{
if (ComputerChoice == "paper")
{
Victory == "Scissors cut paper! You win!";
return Victory;
}
else
{
Victory == "Rock smashes scissors! You lose!";
return Victory;
}
}
}
int main()
{
std::cout << "Rock, Paper, Scissors" << std::endl;
std::cout << "~~~~~~~~~~~~~~~~~~~~~" << std::endl;
std::cout << "Rock: 1" << std::endl;
std::cout << "Paper: 2" << std::endl;
std::cout << "Scissors: 3" << std::endl;
std::string UserChoice, ComputerChoice, Victory;
GetUserChoice( UserChoice );
GetComputerChoice( ComputerChoice );
DetermineWinner( UserChoice, ComputerChoice, Victory);
std::cout << "You picked: " << UserChoice << std::endl;
std::cout << "Computer picked: " << ComputerChoice << std::endl;
std::cout << Victory << std::endl;
system("pause");
return 0;
}
答案 0 :(得分:6)
你不能像这样重新分配函数的参数。您需要使用GetUserChoice
的返回值。摆脱Get
函数的参数,因为它没有做任何事情,而是重新分配,而是将函数的返回值赋给变量:
UserChoice = GetUserChoice();
作为旁注,请查找正确的命名对话。任意变量名称不应该像这样大写。大写标识符主要用于类名。
答案 1 :(得分:2)
你有几个问题:
您应该在分配字符串时错误地比较字符串:
ComputerChoice == "rock";
要将"rock"
分配给ComputerChoice
,请务必使用=
:
ComputerChoice = "rock";
您使用return ComputerChoice;
返回计算机的选择,但在调用GetComputerChoice()
时从未保存该返回值:
GetComputerChoice( ComputerChoice );
相反,您必须将其写为:
ComputerChoice = GetComputerChoice();
请注意,您不需要将任何内容传递给函数;您可以删除std::string ComputerChoice
作为函数参数。
当然,上面的两个示例并不是代码中唯一不正确的地方;您必须完成并修复代码的任何部分,以解决上述问题之一。