#include<stdio.h>#include<stdlib.h>#include<time.h>int diceroll(int num,int side); //返回骰子产生的数字的总和int main(void){ int sets,side,dice; //sets为回合数,side面,dice:骰子个数 int i; //变量初始化 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? \n"); 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<sets;i++) //0-sets个回合 printf("\t%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 sum; int i; srand((unsigned)time(NULL)); for(i=0,sum=0;i<dice;i++) sum+=rand()%side+1; //产生3个骰子 摇出的总和sum return sum; //返回3个骰子摇出的总数sum}
/*
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 <stdio.h>请问为什么srand()不可以加到diceroll的函数中?
追答随机数种子初始化只需一次,反复初始化就会产生重复的数字。