How to generate a random number in C++?

后端 未结 11 1570
萌比男神i
萌比男神i 2020-11-22 11:14

I\'m trying to make a game with dice, and I need to have random numbers in it (to simulate the sides of the die. I know how to make it between 1 and 6). Using



        
11条回答
  •  南旧
    南旧 (楼主)
    2020-11-22 11:46

    This code produces random numbers from n to m.

    int random(int from, int to){
        return rand() % (to - from + 1) + from;
    }
    

    example:

    int main(){
        srand(time(0));
        cout << random(0, 99) << "\n";
    }
    

提交回复
热议问题