C++统计非零数字频率时freq变量无法正确更新问题排查
问题分析与修复
你的代码核心问题是在统计过程中提前修改了当前要输出的数组元素:当内层循环遍历到j=i的位置时,会执行d[j]=0,把当前要统计的数字改成0,导致后续输出d[i]时显示的是0而非原数字。
修复后的代码
#include <iostream> #include <vector> // 用标准容器替代非标准变长数组 using namespace std; int main() { int size; cin >> size; vector<int> d(size); for(int i = 0; i < size; i++){ cin >> d[i]; } for(int i = 0; i < size; i++){ if(d[i] == 0) continue; int current_num = d[i]; // 提前保存当前要统计的数字 int freq = 0; for(int j = 0; j < size; j++){ if(d[j] == current_num){ freq++; d[j] = 0; // 标记为已统计 } } cout << "Frequency of number " << current_num << " is " << freq << endl; } }
关键修复点
- 新增
current_num变量保存当前待统计的数字,避免原数组元素被修改后无法正确输出 - 将
freq的声明移至外层循环内部,无需手动重置,逻辑更简洁 - 替换非标准的变长数组
int d[size]为标准vector<int>,保证代码可移植性
优化建议
嵌套循环的时间复杂度为O(n²),数据量较大时效率偏低。推荐用哈希表实现O(n)时间复杂度的统计,逻辑更清晰且性能更优:
#include <iostream> #include <vector> #include <unordered_map> using namespace std; int main() { int size; cin >> size; vector<int> d(size); unordered_map<int, int> freq_map; // 一次遍历完成统计 for(int i = 0; i < size; i++){ cin >> d[i]; if(d[i] != 0){ // 仅统计非零数字 freq_map[d[i]]++; } } // 输出结果 for(auto& item : freq_map){ cout << "Frequency of number " << item.first << " is " << item.second << endl; } return 0; }
内容的提问来源于stack exchange,提问作者Harinandan N
相关产品推荐
相关产品推荐

