【发布时间】:2015-11-02 02:30:30
【问题描述】:
我编写了这段代码来确定输入的年份是否是闰年。意思是,那些能被 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;
}
}
【问题讨论】:
-
它不应该总是返回
true,因为it shouldn't compile。 -
它绝对可以编译。我正在使用 Visual Studio 2015 Express 版本作为编译器。
-
有趣的是,GCC 也会编译它(带有警告)。但是,从一些阅读来看,我仍然相信 Clang 是对的。编辑:GCC 是错误的,我认为这是因为它仍然接受
false作为空指针常量(即,它允许您执行int* p = false;)。