我正在开发一个项目,我有一个矩阵,我正在通过向上,向下,向左和向右移动一个字符来处理矩阵。我已将移动存储在char数组中。现在我想在对其执行其他移动之后仅打印矩阵的最后10个状态。但我不希望其他动作打印出来,只是矩阵的最后10个状态。
所以我正在循环这样的动作:
int i = 0;
for (; i < strlen(movesArray); i++ ) {
operation = movesArray[i]; // move
switch (operation) {
case 'v': // process the moves
}
然后在for
循环内部,我做了类似的事情:
#ifdef NDEBUG // but this printing every state from 1 to 99
if( i >= strlen(movesArray) - 10)
printf("%s %d:\n", "Move", i );
print(matrix);
#endif
然而它正在打印所有的动作,因为我想要的是迄今为止的最后10个实例。有谁能指导我正确的方向?我现在已经待了几个小时了。
如果我有99次移动,那么它应该执行所有移动但是它应该只打印矩阵的最后10个状态,并且应该包括已经完成矩阵的移动。
我使用-D
标志编译我的程序。
答案 0 :(得分:4)
if
上没有花括号。想一想:
if( i >= strlen(movesArray) - 10)
printf("%s %d:\n", "Move", i ); // No curly braces means only the statement after the
// if is part of the conditional, in this case
// thats this one..
print(matrix);
所以你应该这样做:
if( i >= strlen(movesArray) - 10) {
printf("%s %d:\n", "Move", i );
print(matrix);
} // Everything between the curly braces is part of this conditional.
许多行业都认可编码标准,无论您是多行还是只有一行,都应该始终使用花括号。如上所示,它只添加一行,但可以防止错误的错误like this one。
注意:这是我自己的意见,没有暗示要求。
答案 1 :(得分:2)
您似乎假设printf
语句中的两个标签都在if( ... )
条件的控制之下,它们不在C中。
您需要添加花括号,如下所示。在您的代码示例中,只有第一个printf
受if (...)
的控制。在C中,你需要花括号来包含多个语句。
#ifdef NDEBUG // but this printing every state from 1 to 99
if( i >= strlen(movesArray) - 10)
{
printf("%s %d:\n", "Move", i );
print(matrix);
}
#endif