示例:
diceroll.h
#pragma once extern int roll_count; //引用式声明 int roll_n_dice(int dice, int sides);
diceroll.c
/* 引入标准头文件用<>,引入本地头文件用"" */
#include "diceroll.h"
#include <stdio.h>
/* 提供库函数rand()的原型 */
#include <stdlib.h>
int roll_count = 0; /* 定义式声明,外部链接 */
/* 该函数属于该文件私有 */
static int rollem(int sides)
{
int roll;
roll = rand() % sides + 1;
++roll_count; /* 计算函数调用次数 */
}
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;
}
Main.c
//Visual Studio中加上这句才可以使用scanf()
//否则只能使用scanf_s()
#define _CRT_SECURE_NO_WARNINGS
#include <stdio.h>
#include <string.h>
#include <ctype.h>
//malloc()、free()
#include <stdlib.h>
#include <time.h>
#include "diceroll.h"
//argc: 参数个数 argv[]: 参数数组
//int main(int argc, char **argv)
int main(int argc, char *argv[])
{
int dice, roll;
int sides;
int status;
srand((unsigned int) 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 rollem() function was called %d times.\n",
roll_count); /* 使用外部变量 */
printf("GOOD FORTUNE TO YOU!\n");
system("pause");
return 0;
}
运行测试