加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 百科 > 正文

c – for循环中没有条件?

发布时间:2020-12-16 10:04:50 所属栏目:百科 来源:网络整理
导读:(对不起,这个问题可能非常简单.我把代码写成一个爱好,我只是试着把我的思想包围在一些事情上.) 我最近遇到了一个循环语句,如(n是先前设置的正整数): int cnt;for(cnt=0; n; cnt++){ n = n - 1;} 如果我理解正确,循环中的中间条目应该是一个条件,但是n;似乎
(对不起,这个问题可能非常简单.我把代码写成一个爱好,我只是试着把我的思想包围在一些事情上.)

我最近遇到了一个循环语句,如(n是先前设置的正整数):

int cnt;
for(cnt=0; n; cnt++){
    n &= n - 1;
}

如果我理解正确,循环中的中间条目应该是一个条件,但是n;似乎根本不是一个条件.除非它被理解为bool(如果n!= 0则为true,如果n == 0则为false).如果这是考虑它的正确方法,那么以下代码是否完全等同于上述代码?

int cnt=0;
while(n>0){
    n &= n - 1;
    cnt++;
}

如果是的话,为什么选择以前的写作方式而不是while循环呢?在我看来,while循环将是这里最明确和最直观的选择,所以我想知道我错过的for循环是否有任何优势?谢谢你的任何建议!

解决方法

If I understand correctly,the middle entry in a loop should be a condition,but n; does not seem to be a condition at all.

它是.

Unless if it is understood as a bool (true if n!=0 and false if n==0).

是.

If this is the correct way to think about it,would the following code be perfectly equivalent to the above?

几乎;它是n!= 0,而不是n> 0.

If yes,why would one choose the former style of writing this instead of the while loop?

由于种种原因,人们总是做傻事!

It seems to me that a while loop would be the most clear and intuitive choice here

我同意.

I wonder if there is any advantage in the for loop that I missed?

不.

好吧,不是这个.如果循环体不同,比如使用更复杂的逻辑和一两个continue语句,程序的行为可能会有所不同(如果您忘记在新的代码路径上增加cnt).但事实并非如此.

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读