当我尝试设置已经设置的变量时游戏崩溃

时间:2012-10-13 18:48:55

标签: c++ crash

我试着查找与设置已经设置的变量导致崩溃有关的事情,但我没有找到任何关于此主题的内容。

Rextblock是用户输入的数字。如果textblock等于1,则返回numbermax和2之间的随机数。

if ( textblock == 1 )
{
   int rand1 = rand() %(numbermax - 2) + 2;
   int textbox = rand1;
}

当我为textblock输入1时,它会崩溃,我很确定这段代码会导致它。

using namespace std;

int main(int argc, char *argv[])
{
srand(time(NULL));


int numbermax = 2;



while (while1 < 1)    
{   
cout << "input the number of the text block you wish to use, \n ";
int textblock;
cin >> textblock;

if ( textblock != 0 )
{

}

if ( textblock == 1 )
{
   int rand1 = rand() %(numbermax - 2) + 2;
   int textbox = rand1;
}

if (textblock == 2)
{

}

if (textblock == 2)
{

}


if( textblock == 0 )
{

}   

if ( textblock == 1 )
{
   cout << " \n error, try again \n";     
}

2 个答案:

答案 0 :(得分:1)

我非常怀疑当你运行它时,numbermax等于2.这将导致numbermax - 2等于零,并且使用rhs为0的模数调用除以0,这是未定义的行为,因此崩溃的公平概率。

您应该确保通过if (numbermax != 2)检查确实不会这样做。

答案 1 :(得分:0)

可能你的意思是:

textbox = rand1;

您的代码设置属于if块的局部变量,而不是外部文本框变量。我不知道这会如何导致程序崩溃。