一维数组中数字的频率 [英] Frequency of Numbers in a 1D Array

查看:81
本文介绍了一维数组中数字的频率的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

距离我编写代码已经6个小时了,但无济于事,我不在哪里犯错,但我正在犯错。其频率输出程序和输出应如下所示:

its been 6 hours since I have been writing the code but to no avail, I don't no where I am making the mistake but I am making some. Its a frequency output program and output should be like this:

array[8] = {6,1,7,8,6,6,1,9}

输出:

6:3
1:2
7:1
8:1
9:1

但是它在我的代码中重复相同的数字。任何帮助都是非常有意义的。

But its repeating the same numbers in my code. Any help would be much appreciable.

int array[8] = {6,1,7,8,6,6,1,9};
int store[8];
int a =0;
int b =0;
int c=0;

int d = 0; 
store[d] = array[b];
for (d = 0; d < 8; d++){
  int count=0;
  c = d; 
  b = d; 
  for (int e = 0; e < d; e++){
    if (array[b] == store[e]){
      store[d] = array[b];
      b++;              
      e = 0;            

    }                   
    else   
    {      
      store[d] = array[b]; 
      break;    
    }       
  }        

  for ( int z = 0; z < 7; z++){ 
    if (store[d] == array[z])
    {          
      count++;              

    }                       
  }            
  cout << store[d] << ":" << count << endl;
}


推荐答案

我不确定您正在尝试处理数组。我尝试遵循逻辑,但是很难看到所有匿名变量名。似乎您正在尝试在数组中的较早位置查找重复项,但是变量 e 从未获得除 0 ,因此您将只与数组中的第一项进行比较。

I'm not sure what you are trying to do with the arrays. I have tried to follow the logic, but it's hard to see it with all the anonymous variable names. It seems like you are trying to look for duplicates earlier in the array, but the variable e never gets any other value than 0, so you will only be comparing with the first item in the array.

您只需在数组本身中查找以前的事件,一旦知道数字是第一个出现的事件,您只需要在数组中查找更多出现的事件:

You can just look in the array itself for previous occurances, and once you know that the number is the first occurance, you only need to look for more occurances after it in the array:

int array[8] = {6,1,7,8,6,6,1,9};

for (int i = 0; i < 8; i++) {

  // look to the left in the array if the number was used before
  int found = 0;
  for (int j = 0; j < i; j++) {
    if (array[i] == array[j]) found++;
  }

  // go on if it's the first occurance
  if (found == 0) {

    // we know of one occurance
    int count = 1;

    // look to the right in the array for other occurances
    for (int j = i + 1; j < 8; j++) {
      if (array[i] == array[j]) count++;
    }

    cout << array[i] << ":" << count << endl;
  }
}

这篇关于一维数组中数字的频率的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆