C语言 如何计算while循环执行的次数

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/14310031/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-09-02 05:01:34  来源:igfitidea点击:

How to count the number of times a while loop is executed

cwhile-loop

提问by user1975158

In C, how do you count the number of times a whileloop is executed?

在 C 中,如何计算while循环执行的次数?

In Python, I'd just create an empty list in the beginning and append the values from the whileloop every time the loop is executed. I'd then find the length of that list to know how many times that whileloop was executed. Is there a similar method in C?

在 Python 中,我只是在开头创建一个空列表,并在while每次执行循环时附加循环中的值。然后我会找到该列表的长度以了解该while循环执行了多少次。C中是否有类似的方法?

回答by Oliver Charlesworth

Initialise a variable to 0, and increment it on every iteration?

将变量初始化为 0,并在每次迭代时递增它?

int num = 0;

while (something) {
    num++;

    ...
}

printf("number of iterations: %d\n", num);

回答by sashkello

initiate i = 0and then i++on every loop pass...

启动i = 0,然后i++在每次循环传递...

回答by Roberto

(Sorry, this is the C++ way, not C...) If you really want to go for the filling list, this is how it could be done:

(抱歉,这是 C++ 的方式,而不是 C...)如果你真的想要去填表,可以这样做:

#include <list>
#include <iostream>

using namespace std;

...

   list<int> my_list;
   int num = 0; 
   while( ... ) {
      ...
      ++num;
      my_list.push_back(num);
   }
   cout << "List size: " << my_list.size() << endl;

If you want to print the list values:

如果要打印列表值:

#include <list>
#include <iostream>
#include <algorithm>

using namespace std;

...

   list<int> my_list;
   int num = 0; 
   while( ... ) {
      ...
      ++num;
      my_list.push_back(num);
   }
   cout << "List contens: " << endl;
   // this line actually copies the list contents to the standard output
   copy( my_list.begin(), my_list.end(), iostream_iterator<int>(cout, ",") );