这似乎是一项简单的任务,但出于某种原因,我的代码无法正常工作。 我试过移动部件以查看有什么变化,修复了错误使用的变量,但每次我尝试构建和运行程序时环境仍然崩溃。
这是我的代码:
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
的索引运算符 [],可能会发生两件事。
- 如果键已经存在,它将返回对条目的引用
- 如果键不存在,将创建它并返回对条目的引用。
如果您随后应用++ 后递增运算符,新键或现有键的计数器将增加。您会随处看到此类解决方案。
进一步的必要步骤是,将值转换为字符串,或者更好的是,首先将数字作为字符串读取。然后我们遍历字符串中的字符(数字)并计算它们。
最后,我们展示结果。
请看下面的简单示例代码:
#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/