代码如下:
- #include <iostream>
- using namespace std;
- int main() {
- char ch;
- char s_letter[26]={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
- char b_letter[26]={'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
- int num[26]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
- for (int i = 1; i <= 10000; i++) {
- ch = cin.get();
- if(ch == '#')break;
- for(int j=0;j<=25;j++)
- {
- if(ch==s_letter[j] || ch==b_letter[j]) num[j]++;
- }
- }
- for(int i=0;i<=25;i++)
- {
- cout<<s_letter[i]<<"出现的个数为"<<num[i]<<endl;
- }
- }
(拓展)统计26个字母在一篇新闻中各自出现的频率。
代码如下:
- #include <iostream>
- using namespace std;
- int main() {
- char ch;
- char s_letter[26]={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
- char b_letter[26]={'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
- int num[26]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
- float f_num[26]={0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0,0};
- int Sum;
- for (int i = 1; i <= 10000; i++) {
- ch = cin.get();
- if(ch == '#')break;
- for(int j=0;j<=25;j++)
- {
- if(ch==s_letter[j] || ch==b_letter[j]) num[j]++;
- }
- }
- for(int i=0;i<=25;i++)
- {
- cout<<s_letter[i]<<"出现的个数为"<<num[i]<<endl;
- }
- for(int i=0;i<=25;i++)
- {
- Sum+=num[i]; //计算字母总数
- }
- for(int i=0;i<=25;i++)
- {
- f_num[i]=num[i]*(1.0)/Sum * 100; //计算字母出现的频率*100
- }
- for(int i=0;i<=25;i++)
- {
- cout<<s_letter[i]<<"出现的频率为";
- printf("%.3f",f_num[i]);//保留三位小数
- cout<<"%"<<endl;//输出频率为百分之几
- }
}
(拓展)英文新闻由文件输入,统计其中a-z这26个字母各出现的次数和总字符个数。(不区分大小写)
- #include <iostream>
- #include <fstream>
- #include <cassert>
- #include <string>
- #include<algorithm>
- #include<iomanip>
- using namespace std;
- int main()
- { char s_letter[26]={'a','b','c','d','e','f','g','h','i','j','k','l','m','n','o','p','q','r','s','t','u','v','w','x','y','z'};
- char b_letter[26]={'A','B','C','D','E','F','G','H','I','J','K','L','M','N','O','P','Q','R','S','T','U','V','W','X','Y','Z'};
- int num[26]={0};
- float f_num[26]={0};
- ifstream infile;
- int Sum=0;
- infile.open("C:\\Users\\yyz22\\Desktop\\news1.txt");//打开文件txt 根据自身需求更改绝对路径 注意是双反斜杠\\
- char ch;
- infile >> noskipws;//不跳过空格和换行
- while (!infile.eof())//循环直到文本末尾结束
- {
- infile>>ch;
- cout<<ch;
- for(int j=0;j<=25;j++)
- {
- if(ch==s_letter[j] || ch==b_letter[j]) num[j]++;//统计字母出现个数
- }
- }
- infile.close();
- cout<<endl;
- for(int i=0;i<=25;i++)
- {
- cout<<s_letter[i]<<"出现的个数为"<<num[i]<<endl;
- Sum= Sum + num[i]; //计算字母总数
- }
- cout<<"总数:"<<Sum<<"\n";
- for(int i=0;i<=25;i++)
- {
- f_num[i]=float(num[i])/Sum; //计算字母出现的频率
- }
- for(int i=0;i<=25;i++)
- {
- cout<<s_letter[i]<<"出现的频率为";
- cout<<fixed<<setprecision(6)<<f_num[i]*100;
- cout<<"%"<<endl;//输出频率为百分之几
- }
- }
总结:for循环处理ch=cin.get(); 解决了enter结束输入流的问题。分别用if判断是什么字符或者#结束。
--yyz 1806
2018.10.24