2014-03-03 25 views
2

這令人沮喪,看我只想在用戶輸入'N'或'n'時循環打破。不同while while循環yes或no條件

#include <iostream> 

int main() 
{ 
char abc; 
std::cin >> abc; 

while (abc != 'N' || abc != 'n') 
{ 
     std::cout << "hello world\n"; 
     std::cin >> abc; 
} 
system("pause"); 
return 0; 
} 

這些工作:

while(abc == 'Y' || abc == 'y') 
while(abc == 'N') 

但爲什麼呢?

+0

因爲您輸入的字符不能同時是'N'和'n'。 –

回答

9

變化

while (abc != 'N' || abc != 'n') 

while (abc != 'N' && abc != 'n') 

因爲 (abc != 'N' || abc != 'n')始終爲TRUE。

+0

對......謝謝。 Dumbass me:D – TREMOR

1

De Morgan's Law的應用程序將幫助你在這裏:

!(abc == 'N' || abc == 'n')相同(abc != 'N' && abc != 'n')

您編寫它的方式將導致程序循環:(abc != 'N' || abc != 'n')相當於!(abc == 'N' && abc == 'n'),當然這是!(false)

2

只需更改「||」到「& &」這將工作。

while (abc != 'N' && abc != 'n'). 
0

表達

(abc == 'Y' || abc == 'y') 

的否定可以寫成

!(abc == 'Y' || abc == 'y') 

和改寫爲

(!(abc == 'Y') && !(abc == 'y')) 

,最後作爲

((abc != 'Y') && (abc != 'y')) 

或者乾脆

(abc != 'Y' && abc != 'y') 

所以你的循環控制語句應該被看成

while (abc != 'N' && abc != 'n') 

而且在邏輯上這將是更好地用它替換do-while循環。例如:

#include <iostream> 
#include <cstdlib> 

using namespace std; 

int main() 
{ 
    char abc; 

    do 
    { 
     std::cout << "hello world\n"; 
     std::cin >> abc; 
    } while (abc != 'N' && abc != 'n'); 

    system("pause"); 

    return 0; 
}