2015-10-14 81 views
-2

這是有問題的程序,很短的和甜:爲什麼我的第一個「if」語句不管輸入如何執行?

// Lab 5 Exercise 1 
// Financial Aid Program 
// 
// Written by: Jared T. Fisher 

#include <iostream> 
#include <string> 
using namespace std; 

int main() 
{ 
    long int _income; // declaring the variables 
    char yesNo; 

    cout << "Are you an undergrad student?" ; // determining if they are an undergrad or not. 
    cin >> yesNo; 

    if ((yesNo = 'N') || (yesNo = 'n')) 
    { 
     cout << "You do not qualify for financial aid."; 
    } 

    else if ((yesNo = 'Y') || (yesNo = 'y')) 
    { 
     cout << "What is your current yearly income?"; 
     cin >> _income; 

     if (_income <= 15000 && _income >= 0) // determining which aid they qualify for. 
     { 
      cout << "You qualify for $1000 of financial aid"; 
     } 
     else if (_income > 15000) 
     { 
      cout << "You qualify for $500 of financial aid"; 
     } 
     else 
     { 
      cout << "Your income must be greater than or equal to 0. Please close the program and try again."; 
     } 
    } 

    else 
    { 
     cout << "Your inputted value must be either 'y' or 'n'. Please close the program and try again."; 
    } 

    cout << endl << endl; 
    return 0; 
} // end function main() 

綜上所述,

  1. 如果用戶輸入「n」或「N」,他們馬上告訴他們不」沒有資格。

  2. 如果用戶輸入'y'或'Y',則會詢問他們的年收入,並且從中計算出資格。

  3. 如果用戶輸入除這些輸入以外的任何內容,則會收到錯誤消息。

然而,當我運行這個程序,無論我輸入「N」,「Y」或「棉花糖」,它總是有回報:

"You do not qualify for financial aid." 

,好像我什麼輸入' n'或'N'。我的代碼有什麼問題?

+1

,因爲你犯了一個菜鳥錯誤,而不是用'='賦值的'=='。 – 101010

+0

如果你的編譯器沒有產生大量的警告,你應該拋出並獲得一個新的警告。 –

回答

1

if語句包含分配(yesNo = 'N'等),並給予yesNo非零,它的計算結果true並執行分支。

若要更正此問題,if應包含相等性測試==;

if ((yesNo == 'N') || (yesNo == 'n')) 

你可能會做同樣爲其他if語句。與往常一樣,編譯的最高警告級別爲,編譯器通常會捕獲並警告您這種情況。

一般情況下,可以在if條件下完成分配,但通常不建議使用,因爲它很容易導致錯誤的代碼。

+0

非常感謝! –

0

固定第一if聲明

if ((yesNo == 'N') || (yesNo == 'n')) 

=是賦值運算符,而==是比較操作。

避免這種情況的一種方法是,通過設置相關標誌,編譯器將在這種情況下發出警告。另一種避免它的方式是編碼和仔細觀察。

0

你應該使用比較運算符「==」,而不是賦值操作符「=」

if ((yesNo == 'N') || (yesNo == 'n')) 
{ 
    cout << "You do not qualify for financial aid."; 
} 
0

正如前文所說,如果語句是殘疾人 if ((yesNo = 'N') || (yesNo = 'n'))而不是if ((yesNo == 'N') || (yesNo == 'n'))

針對該類型錯誤的另一個有用的保護是採取與常量的值==操作符的第一個操作數編碼的習慣,那就是if (('N' == yesNo) || ('n' == yesNo))

雖然這個編碼規則是起初並不明顯,任何錯誤(這是一個相當常見的打字錯誤)的比較操作將導致一個編譯器錯誤error: lvalue required as left operand of assignment,無論編譯器警告配置