【问题标题】:change while loop to d-while loop in C [closed]在C中将while循环更改为d-while循环[关闭]
【发布时间】:2020-07-27 13:16:33
【问题描述】:

这是我的代码,有人可以将它从 while 转换为在 c 中执行,非常感谢!!

for(int i=1;i<=31;++i){
            if(hashTables[i]!=NULL){
                printf ("Index %d: %s",i,hashTables[i]->value);
                data *current=hashTables[i];

            while(current->next!=NULL){
                printf (" -> %s",current->next->value);
                current=current->next;
            }
                printf ("\n");
            }   
        }

【问题讨论】:

  • 在您的 specific 情况下,这很简单:将 do 替换为整个 while 行(分号除外),然后删除该 while 行。 (不过,这在其他情况下并不总是有效。)
  • 主要起作用,因为您将测试条件empty==false 设置为正确,以便循环在第一个循环之前立即运行,在empty=false;` 声明。见这里:'do...while' vs. 'while'.
  • 此代码将在数组末尾运行。当key+i 到达m 时,循环本身需要停止。如果您发布minimal reproducible example,您会得到更好的答案。

标签: c loops while-loop do-while dev-c++


【解决方案1】:

只需将do 行替换为源代码的while 行:

while (empty == false) 
{     
   if (ND[key+i] == NULL)
   {
      empty = true;
   }
   else
   {
      ++i;
   }
}

【讨论】:

    【解决方案2】:
    int i=0;
            bool empty;
            empty=false;
    
                if(ND[key+i]==NULL){
                    empty=true;
                }
                else{
                    ++i;
                }
    
            while(empty==false)
                {
                    if(ND[key+i]==NULL){
                    empty=true;
                }
                else{
                    ++i;
                }
                }
            if(key+i<m){
                ND[key+i]=N_Data;
                ND[key+i]->step=i;
            }
        }
    

    【讨论】:

    • if ... else 块在 emtpy=false;while 循环之间是不必要的!循环的第一次运行将实现这一目标。
    • thnx 警告
    猜你喜欢
    • 2020-09-17
    • 1970-01-01
    • 1970-01-01
    • 2020-08-28
    • 2018-08-13
    • 2017-09-26
    • 1970-01-01
    • 1970-01-01
    • 2014-04-05
    相关资源
    最近更新 更多