C ++ if语句错误

时间:2017-08-25 13:34:26

标签: c++

如果满足if语句的要求,我试图将bool leapyear分配给true/false

#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";
    }
}

但是当我运行代码时,视觉显示错误

 Uninitialized local variable 'leapyear' used

2 个答案:

答案 0 :(得分:3)

只需删除boolif块中的两个else,然后为leapyear变量提供初始值。您试图多次定义具有相同名称的变量,而不是仅仅更改其值,这可能就是您想要在此处执行的操作。

初​​始化:

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

if和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

答案 1 :(得分: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";
    }