写出一段C++程序,用来统计一段英文材料中各个英文字母(不区分大小写)出现的百分比。
时间: 2024-02-24 08:53:28 浏览: 24
好的,这是一个简单的 C++ 程序,可以实现你的需求:
```c++
#include <iostream>
#include <string>
#include <map>
#include <cctype>
#include <iomanip>
int main() {
std::string text;
std::cout << "请输入英文材料:\n";
std::getline(std::cin, text);
std::map<char, int> freq;
int total = 0;
for (char c : text) {
if (std::isalpha(c)) {
++total;
++freq[std::tolower(c)];
}
}
std::cout << std::fixed << std::setprecision(2);
for (auto p : freq) {
std::cout << p.first << ": " << (double)p.second / total * 100 << "%" << std::endl;
}
return 0;
}
```
程序的大致思路如下:
1. 读入一段英文材料。
2. 遍历材料中的每个字符,如果它是英文字母,就将它转换成小写字母,并统计它出现的次数。
3. 输出每个字母出现的百分比。
程序用到了 C++ 中的一些常用类和函数,包括:
- `std::string`:用于存储输入的英文材料。
- `std::map`:用于存储每个字母出现的次数。
- `std::isalpha`:判断一个字符是否是字母。
- `std::tolower`:将一个字符转换成小写字母。
- `std::fixed` 和 `std::setprecision`:用于控制输出浮点数的小数位数。