计数器变量出错?

时间:2012-09-26 02:01:35

标签: c++ pearson

我对这段编码中的故障提出了一个简短的问题。

当我运行此程序并进入此循环时(通过输入1作为数字),一切都顺利进行,除非我将++generalcounter1;输入到循环体中,它似乎没有每次循环播放时都要向此变量添加一个。当变量== 10时,它永远不会运行它应该运行的消息。

请帮助我,我非常沮丧!非常感谢您的建议!

很抱歉,如果不清楚,我是这个网站的新手以及编程。

while (number == 1){
 int addend1;
 int addend2;
 int sum;
 int answer1;
 int generalcounter1 = 0;
 int reply1;

 ++generalcounter1;

 addend1 = 1 + rand() % 50;
 addend2 = 1 + rand() % 50;

 sum = (addend1 + addend2);

 cout << "\nWhat is " << addend1 << " plus " << addend2 << "? ";
 cin >> answer1;

 if (answer1 == sum){
     reply1 = winstatement(); 
 }          
 else{
     reply1 = losestatement();
 }

 if (generalcounter1 == 10){

     if (rightanswers >= 8){
        cout << "\nCongratulations, you are ready to go to the next level!\n" << endl;
     }
     else{
        cout << "\nPlease ask your teacher for extra help.\n" << endl;
     }  
  }   
}

1 个答案:

答案 0 :(得分:4)

你在循环的每次迭代中声明一个新的generalcounter1,递增它,并在迭代结束时将其销毁。将声明移动到循环之外,每次都只有一个递增,而不是每次递增一次,直到它再次递增两次。

int generalcounter1 = 0;
while (number == 1) { 
    //loop body
}