查找整数数组中最大的数字出现次数

时间:2013-10-08 00:12:36

标签: c++ arrays find-occurrences

我需要一些关于分配的建议,该分配要求编写一个函数来查找出现最大/最小的偶数位。

我的输出应该如下:

How many integers (to be worked on) ? 2
  Enter integer #1: 1230476
  Enter integer #2: 10034850

Occurrence of all existing digits --
    Digit 0 : 4
    Digit 1 : 2
    Digit 2 : 1
    Digit 3 : 2
    Digit 4 : 2
    Digit 5 : 1
    Digit 6 : 1
    Digit 7 : 1
    Digit 8 : 1
    Digit 9 : 0
Occurence of all existing EVEN digits --
    Digit 0 : 4
    Digit 2 : 1
    Digit 4 : 2
    Digit 6 : 1
    Digit 8 : 1

具有最大发生次数的偶数 - 0

出现次数:4

具有最小发生次数的偶数位 -     2     6     8  并且发生次数:1

这是我的代码到目前为止......我似乎无法找到最大/最小发生的最后一部分..

到目前为止,这是我的代码:     void displayDigitInfoUpdateStanDeng(){

  int intsWorkedOn;
  int* intValue;
  int allDigitCount[10] = {0};
  int largestOccurEven;
  int smallestOccurEven;
  int curDigit;

  cout << "\n  Calling on displayDigitInfoUpdateStanDeng() --"
   << "\n    How many integers (to be worked on) ? ";
  cin >> intsWorkedOn;

  intValue = new int[intsWorkedOn];

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

    cout << "      Enter integer #" << i + 1 << ": ";
    cin >> *(intValue + i);
  }

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

    do {

       allDigitCount[*(intValue + i) % 10]++;

   *(intValue + i) /= 10;
   } while (*(intValue + i));
  }

 cout << "\n    Occurence of all existing digits --";

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


  cout << "\n        Digit " << i << " : " << allDigitCount[i];
}

      cout << "\n    Occurence of all existing EVEN digits --";

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

     cout << "\n        Digit " << i - 1 << " : " << allDigitCount[i++];
}

 cout << "\n   The even digit(s) that has/have the largest occurrence -";

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


   largestOccurEven = allDigitCount[i++] % 10;

   curDigit = allDigitCount[i++];

    if (curDigit < largestOccurEven) {
      cout << "\n    " << i
        << "\n And the number of occurrence(s) : " << largestOccurEven;
    } else {
      cout << endl;
    }
  }

这是我目前的输出:

有多少整数(要处理)? 2       输入整数#1:1230476       输入整数#2:10034850

Occurrence of all existing digits --
    Digit 0 : 4
    Digit 1 : 2
    Digit 2 : 1
    Digit 3 : 2
    Digit 4 : 2
    Digit 5 : 1
    Digit 6 : 1
    Digit 7 : 1
    Digit 8 : 1
    Digit 9 : 0
Occurence of all existing EVEN digits --
    Digit 0 : 4
    Digit 2 : 1
    Digit 4 : 2
    Digit 6 : 1
    Digit 8 : 1

具有最大发生次数的偶数 - 2

出现次数:4

具有最小发生次数的偶数位 -     ?    并且发生次数:0

我很困惑......为什么最大的出现时我显示为2?我真的需要帮助!

1 个答案:

答案 0 :(得分:0)

在你的for循环中执行i++这样的意思就是你在每个步骤中查看不同的“分类”:

largestOccurEven = allDigitCount[i++] % 10;

curDigit = allDigitCount[i++];

你会想避免这样做。例如,将两者都更改为i并适当更改for循环:

for (int i = 0; i < 9; i += 2) {
相关问题