13_掷骰子

模拟一个掷骰子的游戏。
diceroll.c

#include
#include
#include"diceroll.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;
}

diceroll.h

#pragma once
extern int roll_count;
int roll_n_dice(int dice, int sides);

manydice.c

#include
#include
#include
#include"diceroll.h"

int main(void)
{
	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_s("%d", &sides) == 1 && sides > 0)
	{
		printf("How many dices?\n");
		if ((status = scanf_s("%d", &dice)) != 1)
		{
			if (status == EOF)
				break;
			else
			{
				printf("You should have entered an integer.\n");
				printf("Let's begin again.\n");
				while (getchar() != '\n')
					continue;
				printf("How many sides?0 to stop.\n");
				continue;
			}
		}
		roll = roll_n_dice(dice, sides);
		printf("You have rolled a %d using %d %d-sides dice.\n",roll,dice,sides);
		printf("How many sides?0 to stop.\n");
	}
	printf("The rollem() function was called %d times.\n",roll_count);
	printf("bye!\n");
	return 0;
}

运行结果:
13_掷骰子_第1张图片

你可能感兴趣的:(练习代码)