2017-08-25 188 views
-1

我想,如果if語句的要求得到滿足C++的if語句錯誤

#include <iostream> 
using namespace std; 

int main() 
{ 
    int month; 
    int year; 
    bool leapyear; 
    cout << "Enter a month (1-12): "; 
    cin >> month; 
    cout << "Enter a year: "; 
    cin >> year; 

    if (month == 1 || month == 3 || month == 5 || month == 7 || month == 8 || month == 10 || month == 12) { 
     cout << "31 days\n"; 
    } 
    else if (month == 4 || month == 6 || month == 9 || month == 11) { 
     cout << "30 day\n"; 
    } 

    if ((year % 100 == 0 && year % 400 == 0) || (year % 100 != 0 && year % 4 == 0)) { 
     bool leapyear = true; 
     cout << "This year is a leap year!\n"; 
    } 
    else { 
     bool leapyear = false; 
     cout << "This year is not a leap year!\n"; 
    } 

    if (leapyear == true && month == 2) { 
     cout << "29 days\n"; 
    } 
    else if (leapyear == false && month == 2) { 
     cout << "28 days\n"; 
    } 
} 

分配bool leapyeartrue/false但是當我運行的代碼視覺給我一個錯誤

Uninitialized local variable 'leapyear' used 
+0

'bool leapyear = true;'創建一個新變量一樣的名字。改爲使用'leapyear = true;'。 – nwp

+0

錯誤消息告訴你*確切*問題是什麼。你的if語句中的閏年實際上是一個全新的變量。 –

+0

您在2個​​條件條件中再次聲明'leapyear', – EdChum

回答

3

剛刪除ifelse塊中的兩個bool,併爲您的leapyear變量賦予一個初始值。你正試圖用相同的名字多次定義一個變量,而不是僅僅改變它的值,這可能是你想要在這裏做的。

初始化:

int month; 
int year; 
bool leapyear = false; // You have to initialize the value of your variable here. 

如果和else語句:

if ((year % 100 == 0 && year % 400 == 0) || (year % 100 != 0 && year % 4 == 0)) { 
    leapyear = true; 
    cout << "This year is a leap year!\n"; 
} 
else { 
    leapyear = false; 
    cout << "This year is not a leap year!\n"; 
} 

你必須瞭解創建變量並設置其值之間的差異。

bool leapyear = false; // Create a leapyear variable with the initial value false 
leapyear = true; // Modify the value of the leapyear variable with the value true 
+0

哦...那是非常愚蠢的....謝謝你的幫助!讚賞 – CtrlAltDft

2

你的代碼有三個不同的變量,全稱爲leapyear,每個存在的代碼的不同部分。

在你的程序的頂端,你宣稱leapyear

int month; 
int year; 
bool leapyear; // This variable is not initialized. 

下來以後,你聲明更多的變量2,也被稱爲leapyear

if ((year % 100 == 0 && year % 400 == 0) || (year % 100 != 0 && year % 4 == 0)) { 
     // New Variable declared here! 
     // It has the same name, but is a different variable 
     bool leapyear = true; 
     cout << "This year is a leap year!\n"; 
     // The local variable ends here 
     // It goes "out-of-scope", and no longer exists. 
    }       
    else { 
     // New Variable declared here! 
     bool leapyear = false; 
     cout << "This year is not a leap year!\n"; 
     // The Variable goes "out-of-scope" here, and no longer exists. 
    } 

後來,當你的代碼做這個:

// Using the original variable, which is STILL not initialized 
if (leapyear == true && month == 2) { 
     cout << "29 days\n"; 
    } 
    else if (leapyear == false && month == 2) { 
     cout << "28 days\n"; 
    }