我想做一個數獨檢查器函數來查看輸入的棋盤是否有效。要做到這一點,我會生成一個棋盤,然後檢查每個單獨的行,列和9個方格的集合,看它們是否包含數字1-9。如果他們不包含該特定區域中的每個數字,該功能將會在數獨板的行上進行檢查。我不想在檢查編譯版本時輸入全部9行,所以我現在只關注單行。我的循環語句有什麼問題?
該程序檢查該行是否包含全部9個數字。如果該行缺少其中一個數字(1-9),則該函數將顯示return false;
,並顯示「無效的電路板!」。
但是,程序總是說它是一個有效的板,即使它缺少一些所需的數字。
這裏是我的代碼的副本至今:
#include <iostream>
using namespace std;
const int DIMEN = 9;
bool is_valid(int []);
int main()
{
int board[DIMEN];
cout << "Enter values for array.\n";
for (int arraynumber = 0; arraynumber < DIMEN; arraynumber++)
{
cout << "\nArray [" << arraynumber << "]? ";
cin >> board[arraynumber];
}
bool valid = is_valid(board);
if (valid)
{
cout << "\nValid Board!\n";
}
else
{
cout << "\nInvalid Board!\n";
}
return 0;
}
bool is_valid(int isvalid[])
{
bool check_row = false;
//Checks to see if the row has all required numbers
bool check_number = false;
//Checks to see if the row contains a specific number in it
while (!(check_row))
//While the row doesn't yet have all required numbers in it
{
for (int number = 1; number <= DIMEN; number++)
// Goes through each # (1-9) to see if the row contains that #
{
while (!(check_number))
//While the row doesn't yet have the number in it
{
for (int i = 0; i < DIMEN; i++)
//Move across the row from column 0 to 8
{
if (isvalid[i] == number)
/* If the value for this specific element of the array
equals the number */
{
check_number = true;
//The row has the number in it
}
}
if (!(check_number))
/* If the number was not found in the row by the
end of the for loop */
{ return false;
//End the program saying the board is invalid
}
}
}
check_row = true;
}
return true;
}
解決此類問題的正確工具是您的調試器。在*堆棧溢出問題之前,您應該逐行執行您的代碼。如需更多幫助,請閱讀[如何調試小程序(由Eric Lippert撰寫)](https://ericlippert.com/2014/03/05/how-to-debug-small-programs/)。至少,您應該\編輯您的問題,以包含一個[最小,完整和可驗證](http://stackoverflow.com/help/mcve)示例,該示例再現了您的問題,以及您在調試器。 –
當我正在閱讀這篇文章時,我想起了一個想法。閱讀有關程序的循環複雜性。爲了節目減少它是一個好習慣。如果在一段時間內,你有一段時間。無論如何,這不是你的問題。我會看看我能否找到一些 – Makketronix