-2

我面临一个问题

#include<iostream>
using namespace std;
bool check(int input)
{
    int count = 0;
    int temp;
    int val[] = { 2,0,2,1 };
    temp = input;
    while (temp != 0) {
        count++;
        temp /= 10;
    }
    int *arr = new int[count];
    for (int i = count; i >= 0; i--)
    {
        arr[i] = input % 10;
        input /= 10;
    }
    temp = 0;
    int res = count;
    for (int j = 0; j < 5; j++)
    {
        for (int k = 0; k < res; k++)
        {
            if (val[j] == arr[k])
            {
                cout << "CHECKING : " << arr[k] << endl;;
                j = j + 1;
                for (int l = k; l < (count - 1); l++)
                {
                    arr[l] = arr[l + 1];
                }
                res=res-1;
                temp++;
                k = 0;
                if (temp == 4)
                {
                    return true;
                }
            }
        }
    }
    cout << temp;
    return false;
}
int main()
{
    int input;
    cin >> input;
    if (check(input) == true)
    {
        cout <<endl << "YES!!" << endl;
    }
    else
    {
        cout <<endl <<"NO!!" << endl;
    }
}

这个程序我必须检查输入数字是否有 2021 数字如果输入是 2002021 输出应该是或输入是 2002024 输出应该是 no 因为现在缺少 1(2021) 事情是我的程序在逻辑上工作正常但我不知道我的数组最后一个元素是如何丢失的,就像我输入 200022021 = 那么输出将是 no 但是如果我给 200022012 它是说是的,我不知道我的数组的最后一个元素是如何丢失的。

4

2 回答 2

1

你弄错了循环计数器:

for (int i = count; i >= 0; i--)
{
    arr[i] = input % 10;
    input /= 10;
}

在第一次迭代中i == count并且arr[count]超出范围。最后一次迭代i == 1(因为当(i >= 0) == false您停止循环时)并且您从未分配给arr[0].

当您使用std::vectoror std::array(分别用于动态/固定大小)并使用它们的反向迭代器(rbeginand rend)反向迭代所有元素时,您可以调用此类错误历史记录。

于 2020-09-29T16:24:05.100 回答
0

只是因为我懒得寻找错误:

您可以使用与分隔单个数字相同的方法来检查四位数字组中的数字。

x % 10是最后一个数字;x % 100是最后两位数;x % 1000是最后三位数字,依此类推。
添加除以 10 以“移动”数字:

bool check(int input)
{
    while (input > 2020)
    {
        if (input % 10000 == 2021)
        {
            return true;
        }
        input /= 10;
    }
    return false;
}
于 2020-09-29T16:51:43.053 回答