如何在 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;
}