C++ generating random numbers

后端 未结 11 1592
我寻月下人不归
我寻月下人不归 2020-12-01 10:49

My output is 20 random 1\'s, not between 10 and 1, can anyone explain why this is happening?

#include  
#include  
#include <         


        
11条回答
  •  野趣味
    野趣味 (楼主)
    2020-12-01 11:13

    It is one of the simplest logics, got it from a blog. in this logic you can limit the random numbers with that given modulus(%) operator inside the for loop, its just a copy and paste from that blog, but any way check it out:

    // random numbers generation in C++ using builtin functions
    #include 
    
    using namespace std;
    
    #include 
    
    using std::setw;
    
    #include    // contains function prototype for rand
    
    int main()
    {
    // loop 20 times
    for ( int counter = 1; counter <= 20; counter++ ) {
    
        // pick random number from 1 to 6 and output it
        cout << setw( 10 ) << ( 1 + rand() % 6 );
    
        // if counter divisible by 5, begin new line of output
        if ( counter % 5 == 0 )
            cout << endl;
    
    }
    
    return 0;  // indicates successful termination
    
    } // end main
    

    - See more at: http://www.programmingtunes.com/generation-of-random-numbers-c/#sthash.BTZoT5ot.dpuf

提交回复
热议问题