我想做一个数独检查器函数来查看输入的棋盘是否有效。要做到这一点,我会生成一个棋盘,然后检查每个单独的行,列和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