C 字符比较总是错误的

C 字符比较总是错误的,c,char,do-while,C,Char,Do While,我试着做一个简单的do-while循环,其中除“y”或“n”之外的任何字母都是无效的,循环是重复的。有人知道为什么这个循环总是计算为false吗?即使输入了有效字符 char user_response[2]; do { printf("\nDo you want to process another range (y or n): "); scanf("%1s", user_response); user_response[0] = tolower(user_resp

我试着做一个简单的do-while循环,其中除“y”或“n”之外的任何字母都是无效的,循环是重复的。有人知道为什么这个循环总是计算为false吗?即使输入了有效字符

char user_response[2];

do {
    printf("\nDo you want to process another range (y or n): ");
    scanf("%1s", user_response);
    user_response[0] = tolower(user_response[0]);
}
while (user_response[0] != 'y' || user_response[0] != 'n');

return user_response[0];

您应该将| |改为&。

您想使用&&和而不是| |或


这里有两个测试:响应不等于y,响应不等于n。由于响应不能同时为y和n,这些测试中至少有一个将始终为真,并且通过使用或您的while测试将始终评估为真。

如果响应为“y”,则不等于“n”,反之亦然。所以,你的一个或两个表达式都是真的。你的循环测试一个同时是“y”和“n”的假想字符。它不会接受任何不是“y”的东西,也不会接受任何不是“n”的东西。这是更深入的。但是尼姆先回答。不过,感谢您的解释: