我想,如果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 leapyear
到true/false
但是當我運行的代碼視覺給我一個錯誤
Uninitialized local variable 'leapyear' used
'bool leapyear = true;'創建一個新變量一樣的名字。改爲使用'leapyear = true;'。 – nwp
錯誤消息告訴你*確切*問題是什麼。你的if語句中的閏年實際上是一個全新的變量。 –
您在2個條件條件中再次聲明'leapyear', – EdChum