案例4-1.6 树种统计

题目

随着卫星成像技术的应用,自然资源研究机构可以识别每一棵树的种类。请编写程序帮助研究人员统计每种树的数量,计算每种树占总数的百分比。

代码

#include<stdio.h>
#include<stdlib.h>
#include<string.h>
#define N 100
int isContant(char a[N],int x);
void countTreeClass();
int findMinindex();

char string[N][N];
int n;
double count[N];
void main(){
	int i,index;
	//初始化count数组
	for(i=0;i<n;i++)
		count[i]=0;

	scanf("%d",&n);
	getchar();
	countTreeClass();
	for(i=1;i<=n;i++){
		if(findMinindex()){
			index=findMinindex();
			printf("%s %.4lf%% \n",string[index],count[index]/n*100);//注意输出百分号格式,%不能直接输出,%%可以输出
			count[index]=0;//index位置的字符串移除不在参与findMinindex运算

		}else
			break;
	}
	system("pause");
}
void countTreeClass(){
	int i,j,index;
	for(i=1;i<=n;i++){
		gets(string[i]);
		if(isContant(string[i],i)){
			index=isContant(string[i],i);
			count[index]++;
		}else
			count[i]=1;
	}
}
int isContant(char a[N],int x){
	int i;
	for(i=1;i<x;i++){
		
		if(!strcmp(a,string[i])){
			return i;
			break;
		}
	}
	
		return 0;
}
int findMinindex(){
	int i,j,index=0;
	char temp[N];//设temp为最小值串
	//寻找第一个有效字符串的位置
	for(j=1;j<=n;j++){
		if(count[j]){
			index=j;
			break;
		}
	}
	//将第一个有效的字符串赋予最小值串
	strcpy(temp,string[j]);
	//循环搜索之后到字符串有没有比当前字符串小的,如果有则保存当前字符串index并替换为最小串
	for(i=j+1;i<=n;i++){
		if(count[i])
			if(strcmp(string[i],temp)<0){
				index=i;
				strcpy(temp,string[i]);
			}
	}

	return index;

}

总结

1.注意一下scanf()函数输入字符串不能输入空格的问题,换成gets会好一点(之前在网上也百度过说是scanf("%[ ^\n]",string)方式可行,但是我并没有成功)
2.储存字符串的数组建议下标还是从1开始存储,如果从0开始存储,以上代码中Iscontant函数可能会出现0号位置数据无法连续计数的情况。
(PS:如果不是用c来写,换成java用map应该更容易解决)

  • 2
    点赞
  • 4
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值