[英]Can anyone explain the logic behind this simple logic? I'm lost
我只是嘗試在C ++中使用do while循環,而我想出了在do while循環中執行多項操作之后的括號內的描述或其他任何內容的描述。 所以這是我的初始邏輯:我已經設置了password
變量和input
變量。 如果兩個東西匹配,那么它將退出循環並輸出“正確的密碼”,否則它會繼續回到循環,輸出“錯誤的密碼”,所以它繼續。 這是我的代碼:
// do while
#include<iostream>
using namespace std;
int main(){
int input, password=19960819;
do{
cout << "Type your password:" ;
cin >> input;
}while(input!=password && cout << "wrong password" << endl);
cout << "correct password" << endl;
return 0;
}
我期待即使我輸入了正確的答案,我仍然會輸出“錯誤的密碼”。 我認為cout << "wrong password" << endl
部分總是會返回true
,無論如何都應該執行,並且唯一的因素是input!=password
部分。 然而,結果實際上是完美的,這不是我所期待的......任何人都可以解釋邏輯嗎? 我挑戰自己不使用if
或其他邏輯,而只是使用do while
邏輯來達到這個結果,但我不明白為什么它現在正在工作...
C ++對內置的1個布爾運算符使用短路評估 ,這意味着當你這樣做時:
A && B
僅當A
為true
時才評估B
,因為如果A
為false
,則整個表達式為false
(無論B
的值如何)。
所以在:
input != password && cout << "wrong password" << endl
當input != password
為false
(當您輸入正確的密碼時),第二個操作數cout << "wrong password" << endl
未被評估,因此沒有任何輸出。
關於條件評估的額外細節:
input != password
的類型input != password
是bool
; cout << "..." << endl
是std::ostream&
; std::ostream
可以直接轉換為bool
(從C ++ 11開始)或使用轉換為void*
(C ++ 03)。 由於沒有operator&&(bool, [const] std::ostream&)
和std::ostream
可轉換為bool
,因此此處使用內置operator&&(bool, bool)
,因此短路評估適用2 。
當input != password
是true
(你輸入的密碼錯誤), cout << "..." << endl
進行評估,然后轉換成一個bool
值,這將是true
大部分時間3,從而使循環繼續。
當input != password
為false
,短路會阻止cout << "..." << endl
被評估,並且沒有任何內容被發送到輸出。
1對於過載的操作員,短路評估不再適用。 請參見http://en.cppreference.com/w/cpp/language/operator_logical 。
2你可以在main
之前為&&
添加一個用戶定義的重載,例如bool operator&&(bool b, std::ostream &s) { return b && (bool)s; }
bool operator&&(bool b, std::ostream &s) { return b && (bool)s; }
,看到短路僅適用於內置運算符。
3無法保證返回true
,因為流可能處於失敗狀態,但std::cout
不太可能 。
cout << "wrong password" << endl
總是計算為true
(通過轉換為bool
運算符)並具有輸出該文本的副作用。
但是只有input != password
才能評估,因為&&
的短路性質。
真的很可愛。 就個人而言,我會寫
} while (input != password && std::cout << "wrong password\\n");
請注意,這依賴於std::basic_ios::operator bool
,它已從C ++ 11中巧妙地改變。 見http://en.cppreference.com/w/cpp/io/basic_ios/operator_bool 。 在許多方面,最好避免像這樣的華而不實的代碼。
這是因為&&和|| 被評估為短路。 因此,例如,如果A和B都是(並且只有兩者)都為真,A && B將評估為真,但是(這里是短路)如果A或B為假則為假,所以當A為假時,沒有必要評估B.
在您的方案中,當comparaisson'input!= password'為false(即input == password)時,它會停止計算表達式。
希望這可以幫助 :)
對不起我的英語不好。
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.