【问题标题】:How do I calculate how many times were digits used in a chain of integers?如何计算整数链中数字使用了多少次?
【发布时间】:2020-04-09 08:44:13
【问题描述】:

这似乎是一项简单的任务,但由于某种原因,我的代码无法正常工作。 我尝试移动部件以查看发生了什么变化,修复了错误使用的变量,但每次尝试构建和运行程序时环境仍然崩溃。

这是我的代码:

int n, a, dgt, I, II, III, IV, V, VI, VII, VIII, IX;
    cout << "Enter an integer: \n";
    cin >> n;
    a = n;
    while (a > 0)                    // I use this cycle to seperate every number of the chain
    {
        while (n > 0)                // I use this cycle to analyze every number of the chain
        {
            dgt = n % 10;
            n = n / 10;
            if (dgt == 1) I ++;
            if (dgt == 2) II++;
            if (dgt == 3) III ++;
            if (dgt == 4) IV ++;
            if (dgt == 5) V ++;
            if (dgt == 6) VI ++;
            if (dgt == 7) VII ++;
            if (dgt == 8) VIII ++;
            if (dgt == 9) IX ++;
        }

        a--;
    }

如果您能给我任何建议,我将不胜感激:)

【问题讨论】:

  • 欢迎来到 Stack Overflow!听起来您可能需要学习如何使用调试器来逐步执行代码。使用好的调试器,您可以逐行执行您的程序,并查看它与您期望的偏差在哪里。如果您要进行任何编程,这是必不可少的工具。进一步阅读:How to debug small programsDebugging Guide
  • int n, a, dgt, I, II, III, IV, V, VI, VII, VIII, IX; 这些是否已初始化?
  • 你不需要外循环。
  • 看来数组的概念可以大大简化你的程序员生活。
  • 你忘了if (dgt == 0) O ++; 吗?

标签: c++ int digits


【解决方案1】:

有一种或多或少的标准方法来计算一个项目的频率。

使用std::map,其键等于项目和计数器。例如:

std::map<SomeType, size_t> frequencyOfSomeType;

如果使用std::map 的索引运算符[],可能会发生2 种情况。

  1. 如果键已经存在,它将返回对条目的引用
  2. 如果键不存在,则会创建它并返回对该条目的引用。

如果您随后应用 ++ 后自增运算符,则新键或现有键的计数器将增加。你会在各处看到这样的解决方案。

另一个必要的步骤是将值转换为字符串,或者更好的是,首先将数字读取为字符串。然后我们遍历字符串中的字符(数字)并计算它们。

最后,我们展示结果。

请提供下面的简单示例代码:

#include <iostream>
#include <string>
#include <map>

int main()
{
    // Ask user to enter an integer
    std::cout << "Enter an unsigned integer: ";
    if (unsigned long long value{}; std::cin >> value) {

        // convert integer to std::string
        std::string valueString{std::to_string(value)};

        // Now count the digits
        std::map<char,size_t> digitCounter{};
        for (const char& d : valueString) digitCounter[d]++;

        // Ouput result:
        for (const auto& [digit, count] : digitCounter) std::cout << digit << " --> " << count << "\n";
    }
    return 0;
}

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-07-28
    • 2021-12-04
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多