簡體   English   中英

我如何缺少數組的最后一個元素

[英]How am i missing last element of an array

我面臨一個問題

#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 輸出應該是沒有因為現在缺少 1(2021) 事情是我的程序在邏輯上運行良好但我不知道我的數組最后一個元素是如何丟失的,就像我放 200022021 = 那么輸出將是 no 但如果我給 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 (對於動態/固定大小,分別)並使用它們的反向迭代器( rbeginrend )反向迭代所有元素時,您可以調用此類錯誤歷史記錄。

只是因為我懶得去尋找錯誤:

您可以使用與分隔單個數字相同的方法來檢查四位數字組中的數字。

x % 10是最后一位; x % 100是最后兩位數字; x % 1000是最后三位數字,依此類推。
添加除以 10 以“移動”數字:

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

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM