Reputation: 19
*The program is giving wrong output for century year which are not leap Ex.1900,1700.The program is giving wrong output for leap year the value at the load variable is wrong i think Ex.1900,1700. *
#include <iostream>
using namespace std;
int main()
{
int year;
bool t1=true;
cout<<t1;
bool t2=false;
cin>>year;
if(year%4==0)
{
int value=year%100?year%400?t1:t2:t1;
cout<<value;
if(value==t1)
{
cout<<"leap year";
}
else
{
cout<<"not a leap year";
}
}
else
{
cout<<"not a leap year";
}
}
Upvotes: 0
Views: 77
Reputation: 11281
Once C++20 has been properly implemented by compilers (which is not yet in release) you don't have to reinvent the wheel and can use std::chrono::year::is_leap
#include <iostream>
#include <chrono>
int main() {
using namespace std::chrono;
year y = 1900y;
std::cout << "year: " << static_cast<int>(y)
<< " is " << (y.is_leap()?"":"not ") << "a leap year\n";
}
Upvotes: 1
Reputation: 36488
In addition to the fix in MikeCAT's answer you can also significantly simplify your code to just a few lines:
#include <iostream>
int main()
{
int year;
std::cin>>year;
bool leap = (year % 4 == 0) && ( (year % 100 != 0) || (year % 400 == 0) );
if(leap)
{
std::cout<<"leap year";
}
else
{
std::cout<<"not a leap year";
}
}
You can use 0
being equivalent to false
to make it shorter but I think the first version is more readable:
bool leap = !(year % 4) && ( (year % 100) || !(year%400) );
Upvotes: 1
Reputation: 75062
year%100
becomes false when year
is divisible by 100 (the remainder is zero) and becomes true when year
is not divisible by 100 (the remainder is not zero).
year%400
becomes false when year
is divisible by 400 (the remainder is zero) and becomes true when year
is not divisible by 400 (the remainder is not zero).
Therefore, you have to judge the number as not leap year when year%100
is false and year%400
is true, and as not leap year otherwise.
In conclusion, the line
int value=year%100?year%400?t1:t2:t1;
should be
bool value=year%100?t1:year%400?t2:t1;
Also I don't think using int
here to assign bool
variables is reasonable.
Upvotes: 2