我如何错过数组的最后一个元素

问题描述

我遇到了问题

#include<iostream>
using namespace std;
bool check(int input)
{
    int count = 0;
    int temp;
    int val[] = { 2,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输出应该为否,因为缺少1(2021)现在事情是我的程序在逻辑上可以正常工作,但是我不知道数组的最后一个元素是如何丢失的,例如如果我输入200022021 =则输出将为否,但是如果我给出200022012,则表示是的,我不知道数组的最后一个元素是如何丢失的。

解决方法

您弄错了循环计数器:

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

在第一次迭代中,i == countarr[count]越界。最后一次迭代i == 1(因为(i >= 0) == false停止循环)而您从未分配给arr[0]

使用std::vectorstd::array(分别用于动态/固定大小)并使用其反向迭代器(rbegin和{{1})时,可以调用此类错误历史记录})反向迭代所有元素。

,

只是因为我不会因为寻找错误而烦恼:

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

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

bool check(int input)
{
    while (input > 2020)
    {
        if (input % 10000 == 2021)
        {
            return true;
        }
        input /= 10;
    }
    return false;
}