do {
cout << "Enter the account type (C for current and S for savings): ";
cin >> account_type;
} while (account_type != 'S' || 'C');
我已經ACCOUNT_TYPE設置爲char,問題是,每次我運行的程序,我輸入S或C的循環不斷repeating.Can誰能幫助我知道爲什麼它的發生?C++:與有麻煩做while循環
do {
cout << "Enter the account type (C for current and S for savings): ";
cin >> account_type;
} while (account_type != 'S' || 'C');
我已經ACCOUNT_TYPE設置爲char,問題是,每次我運行的程序,我輸入S或C的循環不斷repeating.Can誰能幫助我知道爲什麼它的發生?C++:與有麻煩做while循環
當在布爾操作中使用時,C++中的所有非零值計算爲true
。因此account_type != 'S' || 'C'
與account_type != 'S' || true
相同。這意味着你的循環永遠不會退出。
你需要做的是瓶坯兩個檢查
do {
cout << "Enter the account type (C for current and S for savings): ";
cin >> account_type;
} while (account_type != 'S' && account_type != 'C');
它,因爲你不能說「S」 || 'C',你會認爲C++會認爲你的意思是,如果account_type是S或C,但是C++在兩個獨立的部分看這個:(account_type == 'S') || ('C')
。 ('C')將默認爲true,因此循環將永久循環。
你需要寫的是:
do {
cout << "Enter the account type (C for current and S for savings): ";
cin >> account_type;
} while (account_type != 'S' && account_type != 'C');
您需要更改||到& &,因爲如果account_type是S,那麼它不能是C,反之亦然,因此循環永遠不會結束。
所以&&會像||一樣行事。爲整數? – Akula
@Akula我將它改爲&&的原因是因爲代碼仍然會隨着||而不規則地循環。 &&和||除&&意味着'和'和||之外的整數意味着'或' –
@Akula當你使用||和數字上的&&變成布爾值。如果它不是0,它變成真,如果它變爲0,它變成假。 –
你雖然檢查是錯誤的。你必須把它寫這樣的:
while (account_type != 'S' || account_type != 'C')
您不能執行||
檢查,或任何像,這一問題時,必須始終重新狀態變量。
'account_type!='S'|| 'C''不會做你認爲它做的事。將其更改爲'account_type!='S'|| account_type!='C'' –