dir*_*tly 15
使用以下公式:
M + rand() / (RAND_MAX / (N - M + 1) + 1), M = 1, N = 12
Run Code Online (Sandbox Code Playgroud)
并阅读此常见问题解答.
编辑:关于这个问题的大多数答案没有考虑到差的PRN生成器(通常提供库函数rand()
)在低阶位中不是非常随机的事实.因此:
rand() % 12 + 1
Run Code Online (Sandbox Code Playgroud)
不够好.
#include <iomanip>
#include <iostream>
#include <stdlib.h>
#include <time.h>
// initialize random seed
srand( time(NULL) );
// generate random number
int randomNumber = rand() % 12 + 1;
// output, as you seem to wan a '0'
cout << setfill ('0') << setw (2) << randomNumber;
Run Code Online (Sandbox Code Playgroud)
为了解决这个问题可能会更好吗?
// generate random number
int randomNumber = rand()>>4; // get rid of the first 4 bits
// get the value
randomNumer = randomNumer % 12 + 1;
Run Code Online (Sandbox Code Playgroud)
在mre和dirkgently的评论后编辑