为什么打印此字符值会产生数字

Why does printing this character value produce a number?

本文关键字:数字 打印 字符 为什么      更新时间:2023-10-16
#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,当它必须是 r p 或 s 时。有人看到我哪里出错了吗?

结果int类型(因此它被cout解释为十进制数),你的意思是它具有char类型(因此它被集成为文本字符)。

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

试试这个:

char result;
switch (rand() % 3)
{
case 0: result = c1; break;
case 1: result = c2; break;
case 2: result = c3; break;
}

resultint ,它将存储(和打印)您分配给它的字符的数字表示形式。

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

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

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

尝试对输出使用其他变量。例如:

char response;
if(result==0)
    response = c1;
...
cout << response << end1

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

你最好使用带有开关大小写语句的枚举:

enum Choices { ROCK, PAPER, SCISSORS };

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