69,371
社区成员
发帖
与我相关
我的任务
分享
extern int roll_count;
int roll_n_dice(int dice, int sides);
#include"diceroll.h"
#include<stdio.h>
#include<stdlib.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 -1;
}
if(dice < 1)
{
printf("Need at least 1 die.\n");
return -1;
}
for(d = 0 ; d < dice ; d++)
total += rollem(sides);
return total;
}
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#include"diceroll.h"
int main(void)
{
int dice, roll;
int sides;
int status;
srand((unsigned int)time(0)); // 请问这里的srand()是否没什么用,如果有用,在这个程序什么地方用到?如何使用?
printf("Enter the number or 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-sides 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;
}
/***
*rand.c - random number generator
*
* Copyright (c) Microsoft Corporation. All rights reserved.
*
*Purpose:
* defines rand(), srand() - random number generator
*
*******************************************************************************/
#include <cruntime.h>
#include <mtdll.h>
#include <stddef.h>
#include <stdlib.h>
/***
*void srand(seed) - seed the random number generator
*
*Purpose:
* Seeds the random number generator with the int given. Adapted from the
* BASIC random number generator.
*
*Entry:
* unsigned seed - seed to seed rand # generator with
*
*Exit:
* None.
*
*Exceptions:
*
*******************************************************************************/
void __cdecl srand (
unsigned int seed
)
{
_getptd()->_holdrand = (unsigned long)seed;
}
/***
*int rand() - returns a random number
*
*Purpose:
* returns a pseudo-random number 0 through 32767.
*
*Entry:
* None.
*
*Exit:
* Returns a pseudo-random number 0 through 32767.
*
*Exceptions:
*
*******************************************************************************/
int __cdecl rand (
void
)
{
_ptiddata ptd = _getptd();
return( ((ptd->_holdrand = ptd->_holdrand * 214013L
+ 2531011L) >> 16) & 0x7fff );
}