【发布时间】:2016-10-05 03:36:00
【问题描述】:
我正在尝试制作数独检查器功能以查看输入的棋盘是否有效。为此,我将生成一个板,并检查每个单独的行、列和一组 9 个方格,看看它们是否每个都包含数字 1-9。如果它们不包含该特定区域中的每个数字,则该函数将
return false;
现在,我专注于检查数独板的行数。我不想在检查编译版本时输入所有 9 行,所以我现在只关注一行。
程序检查该行是否包含所有 9 个数字。如果该行缺少其中一个数字 (1-9),它将向函数return false; 并显示“Invalid Board!”。
但是,程序总是说它是一个有效的板,即使它缺少一些必需的数字。
到目前为止,这是我的代码的副本:
#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;
}
【问题讨论】:
-
调试器是解决此类问题的正确工具。 在询问 Stack Overflow 之前,您应该逐行浏览您的代码。如需更多帮助,请阅读How to debug small programs (by Eric Lippert)。至少,您应该 [编辑] 您的问题,以包含一个重现您的问题的 Minimal, Complete, and Verifiable 示例,以及您在调试器中所做的观察。
-
当我读到这篇文章时,我想到了一个想法。阅读程序的圈复杂度。在程序中减少它是一个好习惯。你有如果在一段时间里在一段时间里。无论如何,这不是你的问题。我看看能不能找到东西
标签: c++ loops for-loop while-loop scope