![](/img/trans.png)
[英]C++: Checking whether a string character is a digit using isdigit. .
[英]C++ Checking if a character is not in a string with || not working
我正在開發這個游戲,要求玩家再次玩。 我習慣於檢查條件是否不滿足然后返回 false,所以最后我可以簡單地添加 return true。 這也有助於嵌套。
如果我反過來做,它會起作用:
bool AskToPlayAgain() {
cout << "Do you want to play again? ";
string Response = "";
getline(cin, Response);
if (Response[0] == 'y' || Response[0] == 'Y')
{
cout << "True!\n";
return true;
}
cout << "False!\n";
return false;
}
這將在 y 和 Y 上返回 true,在所有其他字符上返回 False。
然而。 我想要的方式是這樣的:
if (Response[0] != 'y' || Response[0] != 'Y')
{
cout << "False!\n";
return false;
}
cout << "True!\n";
return true;
只是,無論響應如何,它都會始終驗證為 false。 這是為什么? 我該如何解決?
如果你反轉兩邊的條件,你也必須反轉運算符。 也就是說, ||
變成&&
,反之亦然。 (德摩根定律)
想一想: Response[0]
只有一個值,所以它不可能等於兩個值,所以它必須始終不等於兩個值之一。
用簡單的英語,您的代碼要求:
如果“Response”中的第一個字符不是“y”,或者“Response”中的第一個字符不是“Y”,則此表達式為真。
這個說法永遠不可能是假的。 顯然不是“y”或不是“Y”; 它不能同時是兩個值。 兩個不等式之一將始終為真,因此整個表達式也將始終為真。
你應該問的是:
如果“Response”中的第一個字符不是“y”,並且“Response”中的第一個字符也不是“Y”,則此表達式為真。
其中,在 C++ 中,表示為:
if(Response[0] != 'y' && Response[0] != 'Y')
想象一下Response[0] == 'y'
,在這種情況下Response[0] != 'Y'
是true
。 如果Response[0] == 'Y'
條件Response[0] != 'y'
變為true
。 所以你的Response[0] != 'y' || Response[0] != 'Y'
Response[0] != 'y' || Response[0] != 'Y'
始終為true
。
如果Response[0] == 'y'
是𝑨
,並且Response[0] == 'y'
是𝑩
,
然后如下:
if (Response[0] == 'y' || Response[0] == 'Y')
{
cout << "True!\n";
return true;
可以正式寫為(返回true
)
𝑨 ∨ 𝑩
真值表:
𝑨𝑩 𝑨 ∨ 𝑩
00 0 (not 'y' or 'Y')
01 1
10 1
11 1
以及以下內容(不等效):
if (Response[0] != 'y' || Response[0] != 'Y')
{
cout << "False!\n";
return false;
可以正式寫為(答案被反轉,返回false
)
¬(¬𝑨 ∨ ¬𝑩)
真值表(在這個程序中總是假的):
𝑨𝑩 ¬(¬𝑨 ∨ ¬𝑩)
00 0 ok, same as 𝑨 ∨ 𝑩
01 0 not ok, differs from 𝑨 ∨ 𝑩
10 0 not ok, differs from 𝑨 ∨ 𝑩
11 1 ok, but will never happen, Response[0] cannot be both 'y' and 'Y'
現在,為了反轉第一個陳述 ( 𝑨 ∨ 𝑩
),德摩根法則規定:
¬(𝑨 ∨ 𝑩) ⇔ ¬𝑨 ∧ ¬𝑩
或者,等效地:
𝑨 ∨ 𝑩 ⇔ ¬(¬𝑨 ∧ ¬𝑩)
所以,寫¬(¬𝑨 ∧ ¬𝑩)
我們得到:
if (Response[0] != 'y' && Response[0] != 'Y')
{
cout << "False!\n";
return false;
真值表:
𝑨𝑩 ¬(¬𝑨 ∧ ¬𝑩)
00 0 same as 𝑨 ∨ 𝑩
01 1 same as 𝑨 ∨ 𝑩
10 1 same as 𝑨 ∨ 𝑩
11 1 same as 𝑨 ∨ 𝑩
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.