C语言数组的深入应用:字符数组、静态与自动数组及排序算法
1. 骰子滚动程序优化
在之前的骰子滚动程序中,我们需要通过复杂的 switch 语句来统计每个面出现的次数。现在我们可以使用数组来简化这个过程。以下是优化后的代码:
// Fig. 6.9: fig06_09.c
// Roll a six-sided die 60,000,000 times
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define SIZE 7
// function main begins program execution
int main(void)
{
unsigned int frequency[SIZE] = {0}; // clear counts
srand(time(NULL)); // seed random number generator
// roll die 60,000,000 times
for (unsigned int roll = 1; roll <= 60000000; ++roll) {
size_t face = 1 + rand() % 6;
++frequency[face]; // replaces entire switch of Fig. 5.12
}
printf("%s%17s\n", "Face", "Frequency")
超级会员免费看
订阅专栏 解锁全文
298

被折叠的 条评论
为什么被折叠?



