随机数函数和静态变量
#define _CRT_SECURE_NO_WARNINGS
#include
#include
#include
extern unsigned int rand0(void);
int main(void)
{
int count;
for (count = 0; count < 5; count++) {
printf("%dn", rand0());
}
return 0;
}
static unsigned long int next = 1;
unsigned int rand0(void)
{
next = next * 1103515245 + 12345;
return (unsigned int)(next / 65536) % 32768;
}
#define _CRT_SECURE_NO_WARNINGS
#include
#include
#include
extern int rand1(void);
extern void srand1(unsigned int x);
int main(void)
{
int count;
unsigned seed;
printf("Please enter your choice for seed.n");
while (scanf("%u", &seed) == 1) {
srand1(seed);
for (count = 0; count < 5; count++) {
printf("%dn", rand1());
}
printf("Please enter next seed (q to quit):n");
}
printf("Donen");
return 0;
}
static unsigned long int next = 1;
int rand1(void)
{
next = next * 1103515245 + 12345;
return (unsigned int)(next / 65536) % 32768;
}
void srand1(unsigned int seed)
{
next = seed;
}
掷骰子
#include
#include
#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;
}
#pragma once
extern int roll_count;
int roll_n_dice(int dice, int sides);
#define _CRT_SECURE_NO_WARNINGS
#include
#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("%d", &sides) == 1 && sides > 0) {
printf("How many dices?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-sided dice.n",
roll, dice, sides);
}
printf("The rollem() function was called %d times.n",
roll_count);
printf("GOOD FORTUNE TO YOU!n");
return 0;
}
分配内存:malloc()和free()
#define _CRT_SECURE_NO_WARNINGS
#include
#include
#include
int main(void)
{
double* ptd;
int max;
int number;
int i = 0;
puts("What is the maximum number of type double entries?");
if (scanf("%d", &max) != 1) {
puts("Number not correct entered -- bye.");
exit(EXIT_FAILURE);
}
ptd = (double*)malloc(max * sizeof(double));
if (ptd == NULL) {
puts("Memory allocation failed. Goodbye.");
exit(EXIT_FAILURE);
}
puts("Enter the values (q to quit):");
while (i < max && scanf("%lf", &ptd[i]) == 1) {
++i;
}
printf("Here are your %d entries:n", number = i);
for (i = 0; i < number; i++) {
printf("%7.2f ", ptd[i]);
if (i % 7 == 6) {
putchar('n');
}
}
if (i % 7 != 0) {
putchar('n');
}
puts("Done.");
free(ptd);
return 0;
}