我很難轉換字串中每個字符的 ASCII 對應物,
我的目標是轉換每個單詞的平均值,例如:
如果用戶輸入“愛”,代碼將回傳 54,問題是這個代碼在里面一個回圈,如果用戶輸入例如;
1 號字:“愛” 2 號字:“愛”
代碼應該回傳;
54 54
但我的代碼回傳108
我猜問題出在這部分,sum = static_cast<int>(compute - 64);但我不知道我的問題的正確方法
for(int x = 1; x <= numofinput; x ){
cout << "Word no. " << x << ": ";
getline(cin,words);
for(auto compute : words){
if(isalpha(compute)){
compute = toupper(compute);
sum = static_cast<int>(compute - 64);
}
}
}
uj5u.com熱心網友回復:
您需要為sum = 0;您進行計算的每個單詞設定。在此示例中,我還評論了許多其他小問題:
#include <cctype>
#include <iostream>
#include <string>
int main() {
int numofinput = 2;
for(int x = 1; x <= numofinput; x ) {
std::cout << "Word no. " << x << ": ";
if(std::string word; std::cin >> word) { // read one word
int sum = 0; // only count the sum for this word
// auto& if you'd like to show it in uppercase later:
for(auto& compute : word) {
// use unsigned char's with the cctype functions:
auto ucompute = static_cast<unsigned char>(compute);
if(std::isalpha(ucompute)) {
compute = static_cast<char>(std::toupper(ucompute));
sum = compute - ('A' - 1); // 'A' - 1 instead of 64
}
}
std::cout << "stats for " << word << '\n'
<< "sum: " << sum << '\n'
<< "avg: " << static_cast<unsigned>(sum) / word.size() << '\n';
}
}
}
轉載請註明出處,本文鏈接:https://www.uj5u.com/qiye/378898.html
