首页 > 解决方案 > 为什么即使满足条件,While 循环也会在 C++ 中无限执行?

问题描述

我用C++制作了Rolling Dice Program ,它运行良好,除了While 循环没有中断(attempt != 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."; 
}

标签: c++

解决方案


你有两个attempts。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."; 
}

推荐阅读