簡體   English   中英

數組循環不能正常工作? C ++

[英]array loop not working correctly? c++

試圖計算數組中有多少元素不等於0,設置錯了?

我想檢查數組中的所有值(它是一個數獨的板),然后當所有元素都“滿”時,我需要返回true。 什么關閉?

bool boardFull(const Square board[BOARD_SIZE][BOARD_SIZE])
{
    int totalCount=0;
    for (int index1 = 0; index1 < BOARD_SIZE; index1++)
        for (int index2 = 0; index2 < BOARD_SIZE; index2++){ 
             if(board[index1][index2].number!=0)
                totalCount++;
        }
    if(totalCount=81)
        return true;
    else 
        return false;

你有=而不是==

if (totalCount == 81)

是正確的路線。

使用單個“=”執行此操作實際上會將值81分配給totalCount,因此您的測試非常重要:

if (81)

因為在C ++中,任何非零都是真的,這總是如此

你有一個=應該是== 這就是我要說的,因為它是家庭作業。

另外,為什么你有BOARD_SIZE的常數,然后在最后檢查81 不會檢查BOARD_SIZE * BOARD_SIZE會更好嗎?

If(totalCount = 81)是這篇文章或您的代碼中的拼寫錯誤嗎? 看起來你已經在那里分配了價值。

您可以在找到第一個0后立即離開該函數,並且可以通過單個循環解決此問題:

bool boardFull(const Square board[BOARD_SIZE][BOARD_SIZE])
{
    const Square* p = board[0];
    for (int n = BOARD_SIZE * BOARD_SIZE; n; --n, ++p)
    {
        if (p->number == 0) return false;
    }
    return true;
}

但我更喜歡算法到手寫循環:

struct Square
{
    int number;

    bool is_zero() const
    {
        return number == 0;
    }
};

#include <algorithm>
#include <functional>

bool boardFull(const Square board[BOARD_SIZE][BOARD_SIZE])
{
    return std::find_if(
        board[0],
        board[BOARD_SIZE],
        std::mem_fun_ref(&Square::is_zero)
    )== board[BOARD_SIZE];
}

暫無
暫無

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

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