如何用布尔值跳出while循环

How to break out of a while loop with a boolean?

本文关键字:while 循环 何用布      更新时间:2023-10-16

我正试图打破几个嵌套的while循环,我遇到了麻烦。我想让这个程序进入外循环,只运行一定次数。我试着用布尔值来做,但是我的程序终止得太早了。这是一个n皇后问题,我要解1x1 2x2 3x3,等等。nxn皇后区。

下面是我的代码:
bool ok(int *q, int col)
{
   for(int i=0; i<col; i++)
      if(q[col]==q[i] || (col-i)==abs(q[col]-q[i])) return false;
return true;
};
void print(int q[], int n, int cnt)
{
    //static int count =0;
    cout<<"There are "<<cnt<<" solutions for "<<n<<" queens." <<endl;   
};
int main()
{
    int n;
    int *q;
    cout<<"Please enter the size of the board:"<<endl;
    cin>>n;
    int static count = 0;
    int c = 1;
    int a = 1;
    bool from_backtrack=false;
    while(a!=n){
        q= new int[a];
        q[0]=0;
        bool foundSolution=true;
        while(foundSolution)
        {
            if (c==a){
                a++;
            }
            while(c<a)
            {
                if(!from_backtrack)
                    q[c] = -1; //Start at the top
                from_backtrack=false;
                while(q[c]<a)
                {
                    q[c]++;
                    if  (q[c]==a)
                    {
                        c--;
                        if(c==-1) {
                            print(q, n, count);
                            foundSolution=false;
                            //system("PAUSE"); exit(1);
                        }
                        continue;
                    }
                    if( ok(q,c) ) break; //get out of the closest while loop
                }
                c++;
            }
            count++;
            c--;
            if(c==-1) {
                print(q, n, count);
                foundSolution=false;
                //system("PAUSE"); exit(1);
            }
            from_backtrack=true;
        }
        delete[a] q;
        a++;
    }
    system("PAUSE");
}

最优雅的方法是将一些内部循环包装在函数中。这样更容易阅读和控制。

在我的工作中,我们使用MISRA指南,其中规定"…每个while循环只有1次中断"。这导致我重写了ifwhile循环:

bool can_continue = true;
if (can_continue)
{
  status = Do_Something();
  if (status != SUCCESS)
  {
    can_continue = false;
  }
}
if (can_continue)
{
  status = Do_Another_Thing();
  can_continue = status == SUCCESS;
}
//.. and so on.

的想法是设置一个标志为"false",如果执行不能继续。在任何可能导致执行失败的段之后检查它。

while( true ){
    if( condition == true ){
        goto bye;
    }
}
:bye

别把这个放到作业里…

觉得这既疯狂又没用。

然而,假设您想要3次迭代,您将定义一个包含3个元素的bool数组(全部设置为true)。在每次迭代中,将当前元素设置为false,直到到达数组的末尾。