C++の課題

C++で乱数

C++で10個の乱数を発生させて表示しなさい
  • c++で乱数は std::srand()で種を作り、rand()で取得します。
    #include <iostream>     // cout
    #include <ctime>        // time
    #include <cstdlib>      // srand,rand
    using namespace std;
    int main()
    {
            std::srand( time(NULL) );
            for (int i = 0; i < 10; ++i) {
                    cout << rand () << endl;
            }
    
            return 0;
    }

    最初に種を作るところで時間を使っていますので、実行するたびに違う乱数を表示します。

次のページへ