# C Primer Plus 第12章 12.5 掷骰子

2016/12/13 06:23

1、把随机数对6取模，将产生从0到5的整数。

2、加1.新数将为从1到6范围内的整数。

3、为了方便扩展，将步骤1中的数字6用骰子面数来代替。

``````#include <stdlib.h>        /*为rand()函数提供原型*/
int rollem(int sides)
{
int roll;

roll = rand()%sides + 1;
return roll;
}``````

``````/*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("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);

}``````

#include "diceroll.h"

``````//diceroll.h

extern int roll_count;

int roll_n_dice(int dice,int sides);``````

extern int roll_count;    //来自头文件

int roll_count = 0;       //来自源代码文件

``````//manydice.c  --多次掷骰子的模拟程序
//与diceroll.c一起编译
#include<stdio.h>
#include<stdlib.h>        //为srand()提供原型
#include<time.h>          //为time()提供原型
#include"dicerlll.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 die,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 Fortune To You!\n");
return 0;
}``````

``````Enter the number of sides per die,0 to stop.
6
How many dice?
2
You have rolled a 12 using 2 6-sided dece.
How many sides?Enter 0 to stop.
6
How many dice?
2
You have rolled a 4 using 2 6-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() funcation was called 6 times.
GOOD　FORRUNE TO YOU!``````

0
0 收藏

0 评论
0 收藏
0