笔记(7)掷骰子游戏--CPrimer

来源:互联网 发布:手机导航软件 编辑:程序博客网 时间:2024/05/29 11:44
//-------------------------------------------------------------------------------------
//----掷骰子游戏:骰子面数有4、6、8、12和20,允许掷任意个骰子,并且返回点数的总和。
//   采用随机数实现
//说明程序diceroll.c和manydice.c及diceroll.h放在同一文件或同一目录下编译,在VS2010中新建一空项目
//添加对应的程序即可
//diceroll.c---掷骰子的模拟程序
#include"diceroll.h"
#include<stdio.h>
#include<stdlib.h> //为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;
    if(sides< 2)
    {
      printf("Needat least 2 sides.\n");
      return-2;
    }
    if(dice< 1)
    {
    printf("Needat least 1 die.\n");
    return-1;
    }
    for(d = 0; d < dice; d++)
       total += rollem(sides);

     returntotal;
}

------------------------------------------------------------------
//diceroll.h 提供roll_n_dice()的原型并使得roll_count对程序可用
extern int roll_count;

int roll_n_dice(int dice,int sides);
-----------------------------------------------------------------
//manydice.c -- 多次掷骰子的模拟程序
//与diceroll.c一起编译
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include"diceroll.h" //为roll_n_dice()和roll_count函数提供原型
 
int main()
{
   int dice,roll;
   int sides;

   srand((unsigned int)time(0));// 随机化种子
   printf("Enter the number ofsides per die,0 to stop.\n");
  while(scanf("%d",&sides)==1&&sides>0)
   {
   printf("How manydice?\n");
  scanf("%d",&dice);
   roll =roll_n_dice(dice,sides);
   printf("You have rolled a %dusing %d %d-sided dice.\n",roll,dice,sides);
   printf("How many sides? Enter0 to stop.\n");
   }

   printf("The rollem()functionwas called %d times.\n",roll_count);//使用外部变量
   printf("GOOD FORTUNE TOYOU!\n");

   return 0;
}
*/
/*运行结果:
Enter the number of sides per die,0 to stop.
4
How many dice?
2
You have rolled a 5 using 2 4-sided dice.
How many sides? Enter 0 to stop.
6
How many dice?
7
You have rolled a 20 using 7 6-sided dice.
How many sides? Enter 0 to stop.
8
How many dice?
12
You have rolled a 48 using 12 8-sided dice.
How many sides? Enter 0 to stop.
6
How many dice?
2
You have rolled a 5 using 2 6-sided dice.
How many sides? Enter 0 to stop.
0
The rollem()function was called 23 times.
GOOD FORTUNE TO YOU!
Press any key to continue . . .
//**********************************************************************************
0 0