c++程序:查找偶数

C++ Program: Finding even digits

本文关键字:查找 程序 c++      更新时间:2023-10-16

我需要一些帮助我的代码。程序必须找到一个偶数(如果至少有一个)并得到它们的计数。例子:用户输入- 11555249,程序输出-"重复数字是1 (2x次)和5 (3x次)"。

我的程序工作到我输入例如114,然后它显示数字1重复x2次,但如果我输入11455,它不会输出5(它们也在重复),它只会输出重复的最小数字。我将非常感谢任何建议。

   #include <iostream>
using namespace std;
int main()
{
    int stop;
do{
    int n;
    int *myArray;
    int count = 1;

    cout << "Input number: " << endl;
    cin >> n;
    double x = n;
    x = x / 10;
    // Finds the amount of digits in number[inputted]
    while(x > 1)
    {
        x = x/10;
        count++;
    }
    myArray = new int [count];
    // Puts every digit into an array
    for (int i = 0; i < count; i++)
    {
        myArray[i] = n%10;
        n = n / 10;
    }

    int countEvenDigits = 0; // If there are even digits in the number, it will count them.
    // Checking if there are any even digits
    for (int j = 0; j < count; j++)
        for (int h = j + 1; h < count; h++)
        {
            if (myArray[j] == myArray[h])
            {
                 ++countEvenDigits;
                 cout << "Digit that repeats is: " << myArray[j] << " and their amount is: " << countEvenDigits << endl;
            }

        }




    cout << "To continue this program, press - (1); otherwise - (0)" << endl;
    cin >> stop;
    delete[] myArray;
}while (stop == 1);
    return 0;
}

问题是你所谓的'偶数'。您正在将'偶数'分配给数组中的第一位数字:

int even = myArray[0];

然后在某个循环中计数:

int countEvenDigits = 1; // If there are even digits in the number, it will count them.
// Checking if there are any even digits
for (int j = 1; j < count; j++)
{
    if (myArray[j] == even)
        {
        countEvenDigits++;
        even = myArray[j];

        }

}

但实际上你永远不会去到数组的下一个元素(例如:myArray myArray[1],[2]。您需要遍历所有这些,并将每个countEvenDigits存储在一个单独的数组中(而不是单个数组)。然后当你打印出来的时候,

cout << "Digit that repeats is: " << even << " and their amount is: " << countEvenDigits << endl;

你可能需要对数组进行一些循环,然后输出:

for loop..
  if (countEvenDigits[i] > 1){
    cout << myArray[i] << " repeats " << countEvenDigits[i] << " times ";
  }