用C写的模拟掷骰子程序

整理自:《C Primer Plus》第五版

 

此程序包含三个文件:

  diceroll.cpp :包含两个函数 rollem(int)和roll_n_dice(int,int)

  diceroll.h :头文件

  manydice.cpp :主函数所在文件

 

diceroll.cpp文件:

 

//掷骰子的模拟程序
#include "diceroll.h"
#include
#include  //为rand()函数提供类库

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;
	int temp;
	if(sides < 2)   //边数少于2条
	{
		printf("Need at least 2 sides.\n");
		return -2;
	}
   if(dice < 1)  //骰子数少于一个
	{
		printf("Need at least 1 dice.\n");
		return -1;
	}
   printf("\n产生的骰子数:\n");
  for(d = 0; d < dice;d++)
  {
	  temp = rollem(sides);
	  total +=temp;
	  printf("  %d",temp);
  }
  putchar('\n');
  return total;

	
}

 

diceroll.h文件:

 

//diceroll.h
extern int roll_count;   //掷骰子数
int roll_n_dice(int dice,int sides);
 

manydice.c文件

 

 

//manydice.cpp -- 多次掷骰子的模拟程序
//与diceroll.cpp一起编译

#include
#include   //为srand()函数提供原型
#include    //为time()函数提供原型
#include "diceroll.h"  //为roll_n_dice()和roll_count 提供原型

int main(void)
{
	int dice,roll;
	int sides;     //骰子的边数

	srand((unsigned int)time(0));  //随机化种子
	printf("Enter the number of sides per dice,0 to stop.\n");
	while((scanf("%d",&sides) == 1) && sides > 0)   
	{
		printf("how many dice?\n");
		scanf("%d",&dice);    //骰子数
		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 FUTUNE TO YOU !\n");
}

你可能感兴趣的:(C/C++)