为什么在c++中,即使条件满足,While循环仍然无限执行?



我制作了Rolling Dicec++程序,它工作得很好,除了While循环不破坏(try != 6)。它一直无限地填充随机数(1-6),它应该在尝试== 6时停止,但它没有。你能调整一下我的代码并告诉我有什么问题吗?我是一个初学者在c++中,

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
srand(time(0));
int attempt = 1+(rand()%6);   //random number generating for the Attempts
int numOfAt = 0;              //setting value to Number of Attempts
while (attempt != 6 ){
int attempt = 1+(rand()%6);
cout << "You rolled a " << attempt << endl;     //keeps executing this line infinitely
numOfAt++;
}
cout << "It took you " << numOfAt << " attempts to roll a six."; 
}

你有两个attempt。环体内部的attempt从环体外部是不可见的。while (attempt != 6 )在循环体之外(在循环体之前),所以它看到的是第一个attempt,在循环中没有变化。

要修复此问题,请删除循环体内的attempt声明,并覆盖循环前的attempt

#include <iostream>
#include <cstdlib>
#include <ctime>
using namespace std;
int main()
{
srand(time(0));
int attempt = 1+(rand()%6);   //random number generating for the Attempts
int numOfAt = 0;              //setting value to Number of Attempts
while (attempt != 6 ){
attempt = 1+(rand()%6); // remove "int"
cout << "You rolled a " << attempt << endl;     //keeps executing this line infinitely
numOfAt++;
}
cout << "It took you " << numOfAt << " attempts to roll a six."; 
}

您有两个变量,都称为attempt。您正在测试一个并更改另一个。从循环内的int attempt = 1+(rand()%6);中移除int

注意您在while循环中重新定义int attempt,我怀疑这可能是您的问题。我建议你把int attempt改成attempt

不要在while循环中重新定义尝试,因为变量的作用域导致"attempt"比较不匹配。变量(while外部变量和while内部变量)

更新的循环:

while(attempt != 6) {
attempt = 1+(rand()%6); //updated line
.
.
}

最新更新