C++ if 语句错误
C++ if statement error
如果满足 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 daysn";
}
else if (month == 4 || month == 6 || month == 9 || month == 11) {
cout << "30 dayn";
}
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 daysn";
}
else if (leapyear == false && month == 2) {
cout << "28 daysn";
}
}
但是当我运行代码视觉对象时,向我显示错误
Uninitialized local variable 'leapyear' used
只需删除if
和else
块中的两个bool
,并为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
您的代码有三个不同的变量,都称为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 daysn";
}
else if (leapyear == false && month == 2) {
cout << "28 daysn";
}
相关文章:
- 线程,如果else语句,都是错误的上下文切换后,会发生什么
- 无法理解此 return 语句的功能,没有它就会发生运行时错误
- 语句错误:"","标记之前有"预期的')'
- Arduino 用于语句错误。令牌之前的预期')' ';'。如何解决这个问题?
- 带有开关语句的 do-while 循环 -- 无穷循环错误
- 为什么切换 if else 语句的顺序会导致错误?
- 错误:调用 .. at return 语句时没有匹配函数
- 为什么 if 语句在 Java 中"if(1)"给出错误,但在C++中成立?
- 试图避免在 for 循环中出现 if-else 语句,但代码似乎有一些错误
- 如果语句错误地读取字符串,则始终在第一个条件返回
- 表单显示对话框函数错误,并且不执行下面的语句
- 我收到一个断言错误,但是当我编写 cout 语句时,它会消失
- 我可以使用 try catch 语句来捕获任何错误而不是具体错误吗?
- 我在c++中遇到了一个奇怪的错误,其中一个计算2个小整数加法的语句溢出到一个长值中
- Qt SQL LIKE语句返回错误
- 错误:语句无法解析重载函数C++的地址
- 当我通过删除临时节点来释放内存时,我会得到读取访问违规行为.但是只有当我返回错误语句时
- C++显示错误的 constexpr 错误语句
- C++错误:语句无法解析重载函数的地址
- C++:在CodeBlocks上编译和运行的程序可以工作,但从终端它给出错误语句