【问题标题】:how to calculate the average of each string如何计算每个字符串的平均值
【发布时间】:2022-01-15 00:20:51
【问题描述】:

我很难转换字符串中每个字符的 ASCII 对应项, 我的目标是转换每个单词的平均值 例如: 如果用户输入“love”,代码将返回 54, 问题是这段代码在一个循环中,例如,如果用户输入; 第一个词:“爱” 第二个词:“爱” 代码应该返回; 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); 
                }
            }
        }

【问题讨论】:

  • 为什么不立即cout 而不是将值添加到sum
  • "Word no. "getline(cin,words); ...您要阅读一个单词还是单词列表auto compute 使 compute 成为 char。这是你所期望的吗?
  • 不要使用幻数。而不是64,写'@' - 或更好:'A' - 1
  • std::cin &gt;&gt; word; 会读一个单词(并跳过空格)
  • 你正在对所有内容求和,然后在你应该为每个单词做的时候打印最终的总和。

标签: c++ c++11


【解决方案1】:

您需要为每个要计算的单词设置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';
        }
    }
}

【讨论】:

    猜你喜欢
    • 2015-10-15
    • 2022-01-23
    • 2019-05-03
    • 2017-02-16
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多