C++ 计算字母在单词中出现的概率
#include <iostream>
#include <string>
#include <iomanip>
using namespace std;
int main() {
string letter, word;
while (cin >> letter >> word) {
// 将字母和单词都转换为小写字母
for (int i = 0; i < letter.length(); i++) {
letter[i] = tolower(letter[i]);
}
for (int i = 0; i < word.length(); i++) {
word[i] = tolower(word[i]);
}
int count = 0;
for (int i = 0; i < word.length(); i++) {
if (word[i] == letter[0]) {
count++;
}
}
double probability = (double)count / word.length();
cout << fixed << setprecision(5) << probability << endl;
}
return 0;
}
原文地址: https://www.cveoy.top/t/topic/i7K5 著作权归作者所有。请勿转载和采集!