匿名用户
1级
2014-01-02 回答
/*
Enter the number of sets: enter q to stop.
5 9
How many sides and how many dice:3
Here are 5 sets of 3 9-sided throws.
25 18 14 13 17
How many sets? Enter q to stop.
q
Press any key to continue
*/
#include
#include
#include
int diceroll(int num,int side); //返回骰子产生的数字的总和
int main(void) {
int sets,side,dice; //sets为回合数,side面,dice:骰子个数
int i; //变量初始化
srand((unsigned)time(NULL)); // 应在main()初始化随机数种子
printf("Enter the number of sets: enter q to stop.\n"); //set 组
while(scanf("%d",&sets) == 1 && sets > 0) {
printf("How many sides and how many dice:");
if(scanf("%d%d",&side,&dice) == 2) {
printf("Here are %d sets of %d %d-sided throws.\n",sets,dice,side);
for(i = 0;i
printf("%d ",diceroll(side,dice));//打印出返回值
printf("\n");
printf("How many sets? Enter q to stop. \n");
}
else printf("input side,and dice :\n");
}
return 0;
}
int diceroll(int side,int dice) {
int i,sum;
for(i = 0,sum = 0;i
sum += rand()%side + 1; //产生3个骰子 摇出的总和sum
return sum; //返回3个骰子摇出的总数sum
}
追问:
请问为什么srand()不可以加到diceroll的函数中?
追答:
随机数种子初始化只需一次,反复初始化就会产生重复的数字。