This question already has answers here:
How to generate a random integer number from within a range
(11个答案)
6年前关闭。
如何使用C语言生成一个范围(在这种情况下为1-12,包括1和12)之间的随机整数值?
我已经了解了在一定范围内播种(srand())和使用rand()的方法,但是不确定如何去做。
编辑:这是我到目前为止
它在codepad处工作。
(11个答案)
6年前关闭。
如何使用C语言生成一个范围(在这种情况下为1-12,包括1和12)之间的随机整数值?
我已经了解了在一定范围内播种(srand())和使用rand()的方法,但是不确定如何去做。
编辑:这是我到目前为止
# include <stdio.h>
# include <stdlib.h>
# include <time.h>
// Craps Program
// Written by Kane Charles
// Lab 2 - Task 2
// 7 or 11 indicates instant win
// 2, 3 or 12 indicates instant los
// 4, 5, 6, 8, 9, 10 on first roll becomes "the point"
// keep rolling dice until either 7 or "the point is rolled"
// if "the point" is rolled the player wins
// if 7 is rolled then the player loses
int wins = 0, losses = 0;
int r, i;
int N = 1, M = 12;
int randomgenerator();
main(void){
/* initialize random seed: */
srand (time(NULL));
/* generate random number 10,000 times: */
for(i=0; i < 10000 ; i++){
int r = randomgenerator();
if (r = 7 || 11) {
wins++;
}
else if (r = 2 || 3 || 12) {
losses++;
}
else if (r = 4 || 5 || 6 || 8 || 9 || 10) {
int point = r;
int temproll;
do
{
int temproll = randomgenerator();
}while (temproll != 7 || point);
if (temproll = 7) {
losses++;
}
else if (temproll = point) {
wins++;
}
}
}
printf("Wins\n");
printf("%lf",&wins);
printf("\nLosses\n");
printf("%lf",&losses);
}
int randomgenerator(){
r = M + rand() / (RAND_MAX / (N - M + 1) + 1);
return r;
}
最佳答案
您应该使用:M + rand() / (RAND_MAX / (N - M + 1) + 1)
请勿使用rand() % N
(它将尝试将数字从0返回到N-1)。这很差,因为许多随机数生成器的低位比特令人痛苦地是非随机的。 (See question 13.18.)
示例代码:
#include <stdio.h> /* printf, scanf, puts, NULL */
#include <stdlib.h> /* srand, rand */
#include <time.h> /* time */
int main ()
{
int r, i;
int M = 1,
N = 12;
/* initialize random seed: */
srand (time(NULL));
/* generate number between 1 and 12: */
for(i=0; i < 10 ; i++){
r = M + rand() / (RAND_MAX / (N - M + 1) + 1);
printf("\n%d", r);
}
printf("\n") ;
return EXIT_SUCCESS;
}
它在codepad处工作。
关于c - 生成C范围内的随机整数值,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/15962102/