转载请注明出处:http://blog.csdn.net/droyon/article/details/9840409
1、数组测试:输出随机数(种子不唯一),统计随机数,打印直方图
#include<stdio.h>
#include<stdlib.h>
#include<time.h>
#define N 50
#define boolean int
#define true 1
#define false 0
int a[N];
int main(void)
{
gen_random(10, time(NULL));
print_random();
printf("*************统计直方图**************\n");
int times[10] = { };
print_random_and_times(times);
return 0;
}
void gen_random(int upper_bound, int seed)
{
srand(seed);//指定种子
int i;
for (i = 0; i < N; i++) {
a[i] = (rand() % upper_bound);
}
}
void print_random_and_times(int times[])
{
int i, upper_bound = 10;
for (i = 0; i < N; i++) {
// printf("%d ,%d\t",a[i],times[a[i]]);
++times[a[i]];
}
for (i = 0; i < upper_bound; i++) {
printf("%d(%d) \t", i, times[i]);
}
printf("\n");
boolean isEnd = true;
while (isEnd) {
isEnd = false;
for (i = 0; i < upper_bound; i++) {
if ((times[i]--) > 0) {
printf("%s \t", "*");
if (times[i] > 0)
isEnd = true;
} else {
printf("%s \t", " ");
}
}
printf("\n");
}
}
void print_random()
{
int i;
for (i = 0; i < N; i++) {
printf("%d \t", a[i]);
if ((i + 1) % 5 == 0) {
printf("\n");
}
}
}
打印:
7 2 2 5 2
4 0 2 0 4
3 8 2 1 5
6 4 0 3 6
1 9 2 0 0
6 6 3 2 8
3 0 2 5 7
6 1 0 0 1
4 4 1 6 7
8 5 3 0 8
*************统计直方图**************
0(9) 1(5) 2(8) 3(5) 4(5) 5(4) 6(6) 7(3) 8(4) 9(1)
* * * * * * * * * *
* * * * * * * * *
* * * * * * * * *
* * * * * * * *
* * * * * *
* * *
* *
* *
*