-6

whileC では、ループが実行された回数をどのように数えますか?

whilePython では、最初に空のリストを作成し、ループが実行されるたびにループから値を追加します。while次に、そのループが実行された回数を知るために、そのリストの長さを見つけます。Cに同様の方法はありますか?

4

3 に答える 3

13

変数を 0 に初期化し、反復ごとにインクリメントしますか?

int num = 0;

while (something) {
    num++;

    ...
}

printf("number of iterations: %d\n", num);
于 2013-01-14T00:48:01.057 に答える
2

(申し訳ありませんが、これは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;

リスト値を印刷する場合:

#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, ",") ); 
于 2013-01-14T01:05:30.093 に答える
2

開始i = 0し、i++すべてのループパスで...

于 2013-01-14T00:48:34.807 に答える