C++ generating random numbers

后端 未结 11 1567
我寻月下人不归
我寻月下人不归 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:24
    (rand() % highest) + lowest + 1
    
    0 讨论(0)
  • 2020-12-01 11:24

    You are generating a random number (ie (range*rand()/(RAND_MAX + 1.0))) whose value is between -1 and 1 (]-1,1[) and then casting it to an integer. The integer value of such number is always 0 so you end up with the lower + 0

    EDIT: added the formula to make my answer clearer

    0 讨论(0)
  • 2020-12-01 11:28
    random_integer = (rand() % 10) + 1 
    

    That should give you a pseudo-random number between 1 & 10.

    0 讨论(0)
  • 2020-12-01 11:34

    It's much easier to use the <random> library correctly than rand (assuming you're familiar enough with C++ that the syntax doesn't throw you).

    #include <random>
    #include <iostream>
    
    int main() {
      std::random_device r;
      std::seed_seq seed{r(), r(), r(), r(), r(), r(), r(), r()};
      std::mt19937 eng(seed);
    
      std::uniform_int_distribution<> dist(1, 10);
    
      for(int i = 0; i < 20; ++i)
        std::cout << dist(eng) << " ";
    }
    
    0 讨论(0)
  • 2020-12-01 11:36

    Probably "10 * rand()" is smaller than "RAND_MAX + 1.0", so the value of your calculation is 0.

    0 讨论(0)
提交回复
热议问题