没有学过C++的STL,也没有用过map,基本上是把别人代码照抄一遍。
#include <iostream> #include <string> #include <cstring> #include <map> #include<iomanip> using namespace std; int main() { int N; map<string, int> tree; cin >> N; getchar();//原文也提醒了,不加getchar()不能通过,因为第一个接收的字符串为空了 string name; for (int i = 0; i < N; i++) { getline(cin, name); if (tree.find(name) == tree.end()) { tree[name] = 1; } else { tree[name]++; } } map<string, int>::iterator it; for (it = tree.begin(); it != tree.end(); it++) { double perc = (*it).second*1.0 / N * 100; if (it == tree.end()) { cout << (*it).first << " " << fixed << setprecision(4) << perc << '%'; } else cout << (*it).first << " " << fixed << setprecision(4) << perc << '%' <<endl; } return 0; }