头文件
extern int roll_count;
int roll_n_dice(int dice, int sides);
dicerool.c文件
#include "diceroll.h"
#include<stdio.h>
#include<stdlib.h>
int roll_count = 0;//外部连接
static int rollem(int sides)//该函数属于文件所私有
{
int roll;
roll = rand() % sides + 1;
++roll_count;//计算函数调用次数
return roll;
}
int roll_n_dice(int dice, int sides)
{
int d;
int total = 0;
if ("sides<2")
{
printf("Need at least 2 sides.\n");
return -2;
}
if (dice < 1)
{
printf("Need at least 1 die.\n");
return -1;
}
for (d = 0; d < dice; d++)
total += rollem(sides);
return total;
}
主文件:manydice.c
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include"diceroll.h"
int main8(void)
{
int dice, roll;
int sides;
int status;
double* ptd;
ptd = (double*)malloc(30 * sizeof(double));
srand((size_t)time(0));
printf("Enter the number of sides per die,0 to stop.\n");
while (scanf("%d", &sides) == 1 && sides > 0)
{
printf("How many dice?\n");
if ((status = scanf("%d", &dice)) != 1)
{
if (status == EOF)
break;
else
{
printf("You should have entered an integer.");
printf("Let's begin again.\n");
while (getchar() != '\n')
continue;
printf("How many sides?Enter 0 to stop .\n");
continue;
}
}
roll = roll_n_dice(dice, sides);
printf("You have rolled a %d using %d %d-sided dice.\n",
roll, dice, sides);
printf("How many sides? Enter 0 to stop.\n");
}
printf("The rolldm() function was called %d times.\n",
roll_count);
printf("GOOD FROTUNE TO YOU!\n");
return 0;
}