[英]What am I doing wrong in this C++ code?
#include <cstdlib>
#include <ctime>
#include <iostream>
int main()
{
bool newgame;
std::cout << " Ready to waste more family money gambling? y/n ";
std::cin >> newgame;
if (newgame = "n")
{
newgame = false;
return(123);
}
else if (newgame = "y")
{
srand(time(NULL));
int number = rand() % 10;
int guess;
std::cout << "Pick your number ";
std::cin >> guess;
if (guess == number)
{
std::cout << "Winner!";
}
else
{
std::cout << "Loser!";
}
}
}
I don't understand what I've done wrong here, all that happens is the command prompt closes after I type either "y" or "n". 我不明白我在这里做错了什么,所有发生的事情是在我键入“ y”或“ n”后命令提示符关闭。 I've tried everything, from changing the loop types, to even rearranging the code, but everything I try is fruitless.
我已经尝试了一切,从更改循环类型到重新排列代码,但是我尝试的一切都是徒劳的。
a bool
can only hold the values 0 or 1 (true or false). bool
值只能保持0或1(正确或错误)的值。 Try changing newgame
to a char
. 尝试将
newgame
更改为char
。 Also, you're using assignment ( =
) instead of equality ( ==
). 另外,您正在使用赋值(
=
)而不是等于( ==
)。
Also, if you're trying to loop (as I think you implied in your question) you'll want to wrap everything outside your variable declarations in a do...while
loop. 另外,如果您尝试循环(正如我认为您的问题所暗示的那样),则需要在
do...while
循环中将变量声明之外的所有内容包装起来。
The problem is that == is the operator for equality, not = which is for assignment. 问题是==是相等的运算符,而不是=赋值的运算符。 What is happening is that this part here,
发生的是这部分
if (newgame = "n")
{ newgame = false;
return(123);
}
Is executing and exiting with 123. Booleans do not store "yes" and "no" values, they store 1 for true, and 0 for false. 正在执行并以123退出。布尔值不存储“ yes”和“ no”值,它们存储1表示true,0表示false。
看起来不太近,但我看到很多if blah =的东西,我认为您可能想使用==而不是=,=在if语句中执行赋值==进行比较
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.