赞
踩
思路:
然后计算
#include <iostream> #include <string> #include <iomanip> using namespace std; bool IsSeparator(char ch); int CharCount(string str); int WordCount(string sentence); int main(int argc, char **argv) { string sentence; while (getline(cin, sentence)) { if (!sentence.empty()) { int letterNum = CharCount(sentence); // 统计有多少个字符 int wordNum = WordCount(sentence); // 统计有多少个单词 cout << setiosflags(ios::fixed) << setprecision(2) << letterNum * 1.0 / wordNum << endl; } } return 0; } int WordCount(string sentence) { int wordNum = 0; int len = sentence.length(); int i = 0; while (true) { if (IsSeparator(sentence[i])) { while (i <= len - 1 && IsSeparator(sentence[i])) { i++; } } else if (!IsSeparator(sentence[i])) { wordNum++; while (i <= len - 1 && !IsSeparator(sentence[i])) { i++; } } if (i > len - 1) { break; } } return wordNum; } bool IsSeparator(char ch) { if (ch == ' ' || ch == ',' || ch == '.') return true; return false; } int CharCount(string str) { int cnt = 0; for (char c: str) { cnt += (isupper(c) || islower(c)); } return cnt; }
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。