我写了这段代码来确定输入的年份是否是闰年.意思是,那些被4和400整除的是闰年,而100或其他东西则不是.
但是,我的程序总是为布尔值返回true,因此输出将相信每年都是闰年.
到目前为止,这是我的代码:
#include <iostream>
#include <cmath>
#include <string>
#include <iomanip>
using namespace std;
bool leap_year(int year);
int main()
{
int year;
bool leap_year(int year);
cout << "Please input the year in question: ";
cin >> year;
if (leap_year == false)
{
cout << "The year is not a leap year. ";
}
else
{
cout << "The year is a leap year. ";
}
return 0;
}
bool leap_year(int year)
{
if (year % 4 == 0)
{
bool leap_year = true;
}
else if (year % 400 == 0)
{
bool leap_year = true;
}
else if (year % 100 == 0)
{
bool leap_year = false;
}
else
{
bool leap_year = false;
}
if (bool leap_year = false)
{
return false;
}
else
{
return true;
}
}
Run Code Online (Sandbox Code Playgroud)
你正在声明一堆局部变量
else if (year % 100 == 0)
{
bool leap_year = false;
}
Run Code Online (Sandbox Code Playgroud)
只要}括号,此变量超出范围,您存储的值也是如此.
if (bool leap_year = false)
{
return false;
}
Run Code Online (Sandbox Code Playgroud)
这是定义变量leap_year并将其赋值为false.if反过来将评估false,因此它总是会转到其他条件.
我冒昧地重写了一部分程序.您现在可以看到如何对函数进行调用.同样在函数中,局部变量is_leap_year用于存储返回值,最后返回.我也纠正了逻辑,因为之前的第一个%4检查是正确的,并且没有其他if语句将被执行,这不是你想要的.
#include <iostream>
#include <cmath>
#include <string>
#include <iomanip>
using namespace std;
bool leap_year(int year);
int main()
{
int year;
cout << "Please input the year in question: ";
cin >> year;
if (leap_year(year) == false) //Call the function and check if return is false
{
cout << "The year is not a leap year. ";
}
else
{
cout << "The year is a leap year. ";
}
return 0;
}
bool leap_year(int year)
{
bool is_leap_year = false;
if (year % 4 == 0)
{
is_leap_year = true;
}
if (year % 100 == 0)
{
is_leap_year = false;
}
if (year % 400 == 0)
{
is_leap_year = true;
}
return is_leap_year;
}
Run Code Online (Sandbox Code Playgroud)