c++ - 如何计算整数链中使用了多少次数字?

标签 c++ int digits

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

这是我的代码:

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--;
    }

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

最佳答案

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

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

std::map<SomeType, size_t> frequencyOfSomeType;

如果您使用 std::map 的索引运算符 [],可能会发生两件事。

  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;
}

关于c++ - 如何计算整数链中使用了多少次数字?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/59364205/

相关文章:

sql - 在 Firefox 的 SQLite 管理器插件中,大数字未按应有的方式保存

c++ - WinSock 在连接前绑定(bind)导致 WSAEADDRNOTAVAIL - 请求的地址在其上下文中无效

c++ - 我收到错误 "invalid use of incomplete type ' 类映射'

java - 如何修复整数值而不是引发异常?

go - 为什么同样的值用两种方式转换,结果却不同呢?

ios - 始终显示一定数量的数字

c++ - QString 相对于 std::string 的优势

c++ - 是否有对数时间插入、删除和查找(带距离)的排序数据结构?

c - methodtest.c :(. text+0x47): 未定义对 `pritnf' 的引用

javascript - 除非是整数,否则显示两位小数