为什么打印此字符值会产生数字
Why does printing this character value produce a number?
#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;
}
result
是int
,它将存储(和打印)您分配给它的字符的数字表示形式。
有多种方法可以解决此问题,一种是简单地将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,无论变量的类型是什么,那么输出将是一个数字,如果它是一个字符(字符)(我们不关心大小,但我们关心类型),那么输出将是一个字符。因此,为了解决此问题,结果变量类型必须是前面提到的字符。
- 打印数字图案
- 将数字打印成文字
- 为什么有时我输入一个整数,程序将第一个输入的数字打印成十进制数?
- 必须首先打印向量 v1 中最接近整数 x 的数字<int>
- 首先按给定顺序打印所有数字,然后使用 Array 打印所有字符和其他符号
- 我的问题是关于C++中数字和序列的重复以及如何打印它们?
- 编译器始终打印十六进制/八进制数字
- 我想使用哈希图打印非重复的数字;
- 如何在控制台上打印出带有数字 0-99 的简单数组
- 错误含义;以二进制形式打印数字
- 为什么这个程序接受整数和字母数字输入并打印它们? C++ 中的 std::string 也采用整数值吗?
- 列中打印数字时如何避免打印垃圾?
- 如何编写一个程序来打印特定基数的前N个数字
- C++ 在地板函数之后以十六进制打印数字
- C 不将重复数字打印到输出
- 阿姆斯特朗数字打印错误
- 用数字打印所有可能的组合
- 将数字打印为字符串类型的数字
- 如何以特定格式将数字打印到字符串的中间
- 如何将矢量中的数字打印到文件中