c++中Char到Int的转换问题
Problems Converting Char to Int in C++
我正试着玩这个剪刀石头布游戏,但是我无法通过"您已进入line"这条线。
我的教授说我的问题是,当randNumGenerated是int类型时,userChoice是char类型。我试着用下面的代码来转换r,p和s的值:Char r = 'a';Int a = r;
但是得到了"重新定义:不同的基本类型";编译器错误。我不确定该怎么做,因为将变量重新定义为int是我的意图。我想错了吗?如有任何帮助,不胜感激!
int main()
{
char userChoice;
int computer;
int randNumGenerated = 0;
int r = 0;
int p = 0;
int s = 0;
unsigned seed;
cout << "Chose either rock, paper, or scissors" << endl;
cout << "Let r,p,and s represent rock,paper,and scissors respectively " << endl;
cin >> userChoice;
cout << "You entered: " << userChoice << endl;
cout << " " << endl;
seed = time(0);
srand(seed);
randNumGenerated = rand() % 3;
r == 0;
p == 1;
s == 2;
if ((userChoice == 0 && randNumGenerated == 2) || (userChoice == 1 && randNumGenerated == 0) || (userChoice == 2 && randNumGenerated == 1))
{
cout << "You win!";
}
if ((userChoice == 0 && randNumGenerated == 1) || (userChoice == 1 && randNumGenerated == 2) || (userChoice == 2 && randNumGenerated == 0))
{
cout << "You lose!";
}
if ((userChoice == 0 && randNumGenerated == 0) || (userChoice == 1 && randNumGenerated == 1) || (userChoice == 2 && randNumGenerated == 2))
{
cout << "It's a draw!";
}
return 0;
}
这三行没有作用(字面上看,编译器应该警告您这一点):
r == 0;
p == 1;
s == 2;
您可能正在寻找这样的内容:
int userNum = -1;
switch (userChoice) {
case 'r':
userNum = 0;
break;
case 'p':
userNum = 1;
break;
case 's':
userNum = 2;
break;
}
但是,为什么要使用整数呢?如果您使用字符表示,则if语句将更容易阅读:
char randomChosen = "rps"[randNumGenerated];
if ((userChoice == 'r' && randomChosen == 's') || ...) {
std::cout >> "You win!n";
}
只要看一下这个,我就知道这是石头对剪刀。在基于数字的代码中,我必须回头查看转换表。
相关文章:
- 模板类转换问题 - 无法推断调用的函数
- 复制构造函数隐式转换问题
- 与模板 (c++) 相关的转换问题
- 将文件复制到自定义位置,存在字符串转换问题
- 从基指针到派生的强制转换问题
- JNI 日期值转换问题,在C++中获取不同的长整型值
- 类型转换问题
- 拆分 pybind11 模块和自动类型转换问题
- 类型转换问题:返回为整数而不是浮点/类型
- 如何解决ostream_iterator转换问题?
- C++转换问题
- 代码 c++ VS 2010 中的 LPCWSTR 到字符串转换问题
- 罗马数字C++编程转换问题
- C++十进制到时间的转换问题
- C++到 C 的转换问题
- C 复合分配和类型转换问题
- CPP预处理器到C预处理器转换问题
- 将数据类型从C#封送至C++的类型转换问题
- COM对象,并返回QVariant强制转换问题
- C 汇编器转换问题