C ++程序:查找偶数位数

时间:2015-10-25 16:44:13

标签: c++

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

我的程序就像我输入实例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;
}

1 个答案:

答案 0 :(得分: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 [1],myArray [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 ";
  }