简体   繁体   English

For循环与While循环以显示“一个”值(CS50)

[英]For Loop vs While Loop for Displaying “One” Value (CS50)

Watching week 2 of the CS50 lectures (here: https://video.cs50.net/2016/fall/lectures/2?t=84m33s ) where he re-implements strlen by running a while loop over the characters of a string, with this loop (other code redacted): 看着周CS50讲座(此处的2 https://video.cs50.net/2016/fall/lectures/2?t=84m33s ),在那里他重新器具strlen通过运行while在字符串中的字符循环,与此循环(已编辑其他代码):

string s = get_string();
int n = 0;
while (s[n] != '\0')
{
    n++;
}
printf("%i",n);

My question is: can the above be stated in a for loop? 我的问题是:以上内容可以在for循环中说明吗?

I attempted to create one, but because of the way the for loop is formatted, it seems to force output after each iteration, different from the while loop that allows for one output of the loop, once a specific condition is met. 我尝试创建一个,但是由于for循环的格式化方式,它似乎在每次迭代后强制输出,这与while循环不同,后者是在满足特定条件后才允许循环的一个输出。

I'm curious as to whether a for loop can achieve the same "one-time, conditional" output in a case such as this. 我对于这样的情况下for循环是否可以实现相同的“一次性的,有条件的”输出感到好奇。 If I recall correctly, while is unique to C lang and others such as Python have for loops exclusively (tell me if I'm wrong!). 如果我没记错的话, while是C lang独有的, while Python之类的其他独有的for循环(如果我错了,请告诉我!)。

The same can be written using a for loop. 可以使用for循环编写相同的内容。 For example 例如

string s = get_string();
int n = 0;
for ( ; s[n] != '\0'; n++ );
printf("%i",n);

However this for loop with an empty sub-statement can confuse the reader of the code even if it is written something like 但是,带有空子语句的for循环可能会使代码的阅读者感到困惑,即使它写成类似

for ( ; s[n] != '\0'; n++ ) /* empty body */;

or 要么

for ( ; s[n] != '\0'; n++ ) { / *empty body */ }

Usually the same thing can be done in various ways. 通常,同一件事可以通过多种方式完成。 You should select a more expressive construction. 您应该选择更具表现力的结构。 For this task it is better to use the while loop. 对于此任务,最好使用while循环。

Take into account that it would be more correctly to use type size_t instead of the type int for the variable n . 请注意,对于变量n使用size_t类型而不是int类型会更正确。

For example 例如

string s = get_string();
size_t n = 0;
for ( ; s[n] != '\0'; n++ );
printf("%zu",n);

This code will also work in this case: 此代码在这种情况下也将起作用:

int n=0;
for(;s[n];n++);
printf("%d ",n);

how this works: 工作原理:

String elements has ASCII values, so till the string has characters in it, condition part of for loop is true. 字符串元素具有ASCII值,因此,直到字符串中包含字符为止,for循环的条件部分为true。 As it reaches to end of string ie '\\0' (the integer value of '\\0' is zero), condition fails, loop exits. 当它到达字符串的末尾,即“ \\ 0”(“ \\ 0”的整数值为零)时,条件失败,循环退出。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM