C++ 为什么打印此字符值会产生一个数字? #包括 #包括 #包括 使用名称空间std; int main() { //初始化计算机的随机数生成器 srand(时间(0));rand(); //声明变量 字符c1; 字符c2; 炭c3; c1=‘R’; c2=‘P’; c3=‘S’; //起动回路 while(true) { //决定计算机的选择 int result=rand()%3;//0或1或2 如果(结果==0) 结果=c1; 如果(结果==1) 结果=c2; 如果(结果==2) 结果=c3; //提示并阅读人类的选择 人的选择; 人类选择; 忽略(1000,10); //如果人类想退出,就打破循环 if(humanChoice=='Q')中断; //打印结果 cout

C++ 为什么打印此字符值会产生一个数字? #包括 #包括 #包括 使用名称空间std; int main() { //初始化计算机的随机数生成器 srand(时间(0));rand(); //声明变量 字符c1; 字符c2; 炭c3; c1=‘R’; c2=‘P’; c3=‘S’; //起动回路 while(true) { //决定计算机的选择 int result=rand()%3;//0或1或2 如果(结果==0) 结果=c1; 如果(结果==1) 结果=c2; 如果(结果==2) 结果=c3; //提示并阅读人类的选择 人的选择; 人类选择; 忽略(1000,10); //如果人类想退出,就打破循环 if(humanChoice=='Q')中断; //打印结果 cout,c++,loops,random,C++,Loops,Random,结果的类型为int(因此cout将其解释为十进制数),您的意思是它的类型为字符(因此它被解释为文本字符) 此外,您还有“重载”result,首先保存rand()%3的值,然后再保存字符值。一般来说,最好将变量分开以便于可读性—优化器可以为它们重新使用相同的存储以节省堆栈空间 试试这个: #include <ctime> #include <cstdlib> #include <iostream> using namespace std; int main(

结果的类型为int(因此cout将其解释为十进制数),您的意思是它的类型为字符(因此它被解释为文本字符)

此外,您还有“重载”result,首先保存
rand()%3
的值,然后再保存字符值。一般来说,最好将变量分开以便于可读性—优化器可以为它们重新使用相同的存储以节省堆栈空间

试试这个:

#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;
}

result
int
,它将存储(并打印)指定给它的字符的数字表示形式

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


更好的方法是,imho,首先进行轻微的重构,以获得人工输入,然后根据计算机的选择采取行动(最好是使用
开关
)。

83指的是unicode值“s”。由于结果是int,当您将字符“s”分配给结果时,它将转换为int。因此,它输出83

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

char result;

switch (rand() % 3)
{
case 0: result = c1; break;
case 1: result = c2; break;
case 2: result = c3; break;
}
char响应;
如果(结果==0)
响应=c1;
...

cout您正在接受的输入是字符类型。将其转换为整数将得到相关字符的ASCII值。p的ASCII值为80,R为82,S为83

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

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

<>你的结果是int,不是char。与你的问题无关:当你的意思是<代码> \n′/Cube时,千万不要说<代码> EntL\/Cube。在你的情况下,你在打印<代码>结果< /代码>之后不必要地冲洗输出流。C++有很多隐式的转换。你看到的是ASCII值。@迈克:不一定,但最有可能:嗯,真的很感激!我很困惑83号是从何而来的。
enum Choices { ROCK, PAPER, SCISSORS };