数据结构与算法题目集(中文)7-24 树种统计 (25分)

1.题目

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

输入格式:

输入首先给出正整数N(≤10​5​​),随后N行,每行给出卫星观测到的一棵树的种类名称。种类名称由不超过30个英文字母和空格组成(大小写不区分)。

输出格式:

按字典序递增输出各种树的种类名称及其所占总数的百分比,其间以空格分隔,保留小数点后4位。

输入样例:

29
Red Alder
Ash
Aspen
Basswood
Ash
Beech
Yellow Birch
Ash
Cherry
Cottonwood
Ash
Cypress
Red Elm
Gum
Hackberry
White Oak
Hickory
Pecan
Hard Maple
White Oak
Soft Maple
Red Oak
Red Oak
White Oak
Poplan
Sassafras
Sycamore
Black Walnut
Willow

输出样例:

Ash 13.7931%
Aspen 3.4483%
Basswood 3.4483%
Beech 3.4483%
Black Walnut 3.4483%
Cherry 3.4483%
Cottonwood 3.4483%
Cypress 3.4483%
Gum 3.4483%
Hackberry 3.4483%
Hard Maple 3.4483%
Hickory 3.4483%
Pecan 3.4483%
Poplan 3.4483%
Red Alder 3.4483%
Red Elm 3.4483%
Red Oak 6.8966%
Sassafras 3.4483%
Soft Maple 3.4483%
Sycamore 3.4483%
White Oak 10.3448%
Willow 3.4483%
Yellow Birch 3.4483%

2.题目分析

1.使用map

 2.getchar();//当有string类型的输入前面有其他类型输入时,用getchar()吃回车

3.cin不接受空格,TAB等键的输入,遇到这些键,字符串会终止 

4.char[]可用gets(),string类型的只能用getline(cin,s)

5.保留4位小数:

printf("%.4f%%", temp);

 或者

#include<iomanip>

cout << fixed << setprecision(4) << temp <<"%"<< endl;

6.引申:四舍五入方法:

四舍五入:保留整数 int a = b+0.5;

       保留一位小数  int a=(b+0.05)*10;

            double c=a/10;

       保留二位小数  int a=(b+0.005)*100;

            double c=a/100;

(上面的方法仅适用于正数。)

如果需要对负数进行转换,可以为这个负数加上一个足够大的正整数,使得和变成正数,然后四色五入后再减去前面加上的正整数就好

如: 对 -3.4进行四舍五入

    double a = -3.4+5 = 1.6

    int b = (1.6+0.5) = 2

    int answer = 2 -5 = -3

这儿有个坑, 如 -3.5, 四舍五入应该是-3 而不是-4

强制保留两位小数:include<iomanip>

          cout<<setiosflags(ios::fixed)<<setprecision(2)<<a<<endl; 

3.代码

#include<iostream>
#include<map>
#include<string>
#include<iomanip>
#include<cstdio>
using namespace std;
int main()
{
	int amount = 0;
	cin >> amount;
	map<string,int>list;
	getchar();////当有string类型的输入前面有其他类型输入时,用getchar()吃回车
	for (int i = 0; i < amount; i++)
	{
		string temp;
		getline(cin, temp);//cin不接受空格,TAB等键的输入,遇到这些键,字符串会终止
                      //char[]可用gets(),string类型的只能用getline(cin,s)
		list[temp]++;
	}

	map<string,int>::iterator run;
	double n = amount + 0.0;
	for (run = list.begin(); run != list.end(); run++)
	{
		double temp;
		temp = (*run).second / n;
		temp = temp * 100;
		cout << (*run).first << " ";
		//cout << fixed << setprecision(4) << temp <<"%"<< endl;
        printf("%.4f%%\n", temp);
	}



}
发布了37 篇原创文章 · 获赞 1 · 访问量 264

猜你喜欢

转载自blog.csdn.net/qq_42325947/article/details/104226534