Linux C一站式学习习题答案8.3.1直方图

1、补完本节直方图程序的main函数,以可视化的形式打印直方图。例如上一节统计20个随机数的结果是:

0  1  2  3  4  5  6  7  8  9

*  *  *  *     *  *  *     *
*     *  *     *  *  *     *
      *  *        *
                  *
                  *
#include <stdio.h>
#include <stdlib.h>
#include <time.h>
#define N 10
#define min 0
#define max 10
#define band 10

int a[N], histogram[band], i;


int gen_rand(int bound) // 产生0~bound范围内的随机数
{
	srand(time(NULL));
	for (i = 0; i < N; i++)
		a[i] = rand() % bound;

	return 0;
}
/*
int howmany(int value) // 统计a中等于value的数的个数
{
	int count = 0;

	for (i = 0; i < N; i++) 
	{
		if (value == a[i]) 
		{
			++count;
		}
	}
	return count;	
}
*/
char star(int i) 
{
	char star;

	if (i <= 0)
		star = ' ';
	else
		star = '*';
	return star;
}

int get_max (int a, int b) // 返回a、b中的较大值
{
	if (a < b)
		a = b;
	return a;
}
int main()
{
	gen_rand(band);
	int i = 0, histogram[10] = {0};
	int max_histogram = 0;
	for (i = 0; i < N; i++)
		histogram[a[i]]++;
	
	for (i = 0; i < 10; i++)
		printf ("%d\t", i);	//打印随机数
	printf ("\n");
	for (i = 0; i < 10; i++)
	{
		printf ("%d\t", histogram[i]); // 打印每个随机数的频数
		max_histogram = get_max (histogram[i], max_histogram);
	}
	printf ("\n\n");

	while (max_histogram>0) 
	{
		for (i = 0; i < 10; i++) 
		{
			printf ("%c\t", star(histogram[i])); //打印直方图
			histogram[i] = histogram[i] - 1;
		}
		printf ("\n");
		max_histogram--;
	}
	return 0;
}
注:转载请注明源地址:http://blog.csdn.net/whorus1/article/list/2,谢谢!




评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值