题目
随着卫星成像技术的应用,自然资源研究机构可以识别每一棵树的种类。请编写程序帮助研究人员统计每种树的数量,计算每种树占总数的百分比。
代码
#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应该更容易解决)