![](/img/trans.png)
[英]Why does my empty loop run twice as fast if called as a function, on Intel Skylake CPUs?
[英]C - Why does this loop run through twice?
该函数假设在连接4游戏中返回了第一步,但是它又返回了两次……我通过调试器进行了该函数的测试,似乎跳过了不知道为什么的getc()调用。 任何帮助深表感谢!
char UndoBoard(char x[ROWS][COLS], char * player){
struct Node* temp = head;
int i,j;
temp = temp->next;
char input = 'q';
while((input != 'q' || input != 'Q') && temp != NULL){
for (i=0;i<ROWS;i++){
for (j=0;j<COLS;j++){
x[i][j] = temp->data[i][j];
}
}
printBoard(x);
if(*player == 'O')*player = 'X';
else *player = 'O';
printf("b - undo one step more, f - go forward, q - resume game from here\n");
input = getc(stdin);
if(input == 'q' || input == 'Q')break;
temp = temp -> next;
}
}
用于的逻辑
while((input != 'q' || input != 'Q') && temp != NULL){
有毛病。 您需要使用:
while((input != 'q' && input != 'Q') && temp != NULL){
您在while
条件中input
的条件是错误的。 无论input
的值如何,这两项都是正确的,因此,仅当temp != NULL
,循环才会在此处终止。
但是实际上您稍后会在循环中使用正确的表达式break
用户输入,因此实际上不需要在循环条件下进行测试。 而是在这里仅使用temp
:
while ( temp != NULL ) {
现在你也可以改变
char input = 'q';
至
char input;
因为现在不是在循环中读取用户输入之前。
请注意, getc
返回一个int
,而不是提供EOF
的char
,您也应该进行测试。 (感谢@chux指出了这一点)。
在循环中使用它时,可以将其移动到(包括所有更改):
while ( temp != NULL ) {
int input;
...
if ( input == EOF || input == 'q' || input == 'Q' )
break;
temp = temp->next;
}
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.