0
#include <ctime>
#include <cstdlib>
#include <iostream>
using namespace std;


int main()
{
  // initialize the computer's random number generator
  srand(time(0)); rand();

  // declare variables
  char c1;
  char c2;
  char c3;

  c1 = 'R';
  c2 = 'P';
  c3 = 'S';

  // start loop
  while (true)
  {

    // determine computer's choice
    int result = rand() % 3; // 0 or 1 or 2

    if (result == 0) 
      result = c1;

    if (result == 1) 
      result = c2;

    if (result == 2) 
      result = c3;

    // prompt for, and read, the human's choice

    char humanChoice;
    cout << "Rock, Paper, or Scissors? [R/P/S or Q] ";
    cin >> humanChoice;
    cin.ignore(1000, 10);

    // if human wants to quit, break out of loop
    if (humanChoice == 'Q') break;


    // print results
    cout << result << endl;
    cout << humanChoice << endl;

  // end loop
  }

  // end program 



  return 0;
}

伙计们怎么了?我正在进行我的中期项目的第一步,即创建一个石头剪刀布游戏。这只是开始,我还远未完成,但我已经遇到了错误。当我编译并运行它时,我得到计算选择了数字 83,它必须是 rp 或 s。有谁看到我哪里出错了?

4

5 回答 5

2

resultint类型(因此它被 cout 解释为十进制数),您的意思是它具有char类型(因此它被解释为文本字符)。

此外,您还有“重载”结果,首先保存rand() % 3字符值,然后保存字符值。通常,最好将变量分开以提高可读性 - 优化器可以计算出为它们重用相同的存储空间以节省堆栈空间。

尝试这个:

char result;

switch (rand() % 3)
{
case 0: result = c1; break;
case 1: result = c2; break;
case 2: result = c3; break;
}
于 2012-04-07T20:28:05.037 回答
0

resultis int,它将存储(并打印)您分配给它的字符的数字表示。

有多种方法可以解决这个问题,一种是简单地更改resultchar. 您仍然可以在其中存储数字(限制为 0-255)并且将获得正确的输出。

恕我直言,更好的方法是稍微重构一下,首先获取人工输入,然后根据计算机的选择采取行动(最好使用 a switch)。

于 2012-04-07T20:29:33.993 回答
0

83 指的是 's' 的 unicode 值。由于 result 是一个 int,因此当您将 char 's' 分配给 result 时,它会被强制转换为一个 int。因此,它输出 83。

尝试为输出使用不同的变量。例如:

char response;
if(result==0)
    response = c1;
...
cout << response << end1
于 2012-04-07T20:31:24.710 回答
0

cout << 东西超载了。int 和 char 的行为不同。如果它是一个 int 变量的类型,那么输出将是一个数字,如果它是一个 char(字符)(我们不关心大小,但我们关心类型),那么输出将是一个人物。因此,为了解决这个问题,结果变量类型必须是前面提到的 char。

于 2012-04-07T20:38:05.427 回答
0

您正在接受的输入是 char 类型。将其转换为整数将为您提供相关字符的 ASCII 值。P 的 ascii 值为 80,R 为 82,S 为 83。

最好使用带有 switch-case 语句的枚举:

enum Choices { ROCK, PAPER, SCISSORS };
于 2012-04-07T20:32:17.503 回答