# C++ is seemingly doing division incorrectly

I am trying to make a program to check if any given year is a leap year, I found the (n % 2 == 0) equation and it was great but as soon as I put it in a Boolean and then the bool in an if else statement it started giving me numbers that don’t make sense, I tried to reverse engineer the numbers but
I can’t make any sense out of why it spitting those numbers out.
I#include
int main() {
//variables
int year = 2020;
//check if divisible by four
std::cout << "Enter year: ";
std::cin >> year;

//Years leap check
bool divfour = (year % 4 == 0);
bool divqhund;
if (year % 100 == 0) {
bool divqhund = (year % 400 == 0);
}
//Print Years leap state

if (divqhund){
std::cout << divqhund;

}
else if(divfour){
std::cout << “S 4”;
}
else {
std::cout << “F”;
}
}

TERMINAL
Enter year: 1700
S 400\$ g++ leap_year.cpp
\$ ./a.out
Enter year: 1700
10\$ ./a.out
Enter year: 1600
61\$ ./a.out
Enter year: 2020
104\$ ./a.out 2020
Enter year: 2020

Look into formatting this as it’s hard to read.

I think you need to narrow down what your expectation of the modulo operator is (it’s not division).

All ab (mod m) is saying is that there exists a `k` for which . ab = km.

91 (mod 4) precisely because we can find a k such that 9-1 (8) is k*4. (k would be 2 here).

In C++ this would be written 9 % 4 which evaluates to 1.

Also consider how you’re formatting your print statements.

``````bool divqhund;
if (year % 100 == 0)
{
bool divqhund = (year % 400 == 0);
}
``````

This is an issue.
You create a differently scoped divqhund. Which one should be the real one?

I am confused, how could it a - b = km? the equation is a % b == 0. 0 not km. also what is the point of local and global values.

It’s the mathematical definition from where % comes from (Modular arithmetic - Wikipedia). In the long run it helps knowing some basic number-theoretic things so to be exposed to the mathematical definition is not a bad thing.

For example, my co-worker was writing a function to count how many days have passed in the month that were a particular weekday. They had a bunch of ifs and and elses. But there is a simple one line math function that can just return the result without further complication. (all this to say is that it can be useful to know these things exist and what their properties are).

Local and global variables are just that. Sometimes you want something to be scoped at a different level and want to avoid name clashing while keeping the values different. In my opinion it’s just better to use different variable names in that case.

Your code should probably be (from what you are wanting)

``````bool divqhund;
if (year % 100 == 0)
{
divqhund = (year % 400 == 0);
}
``````

but it’s useful to know that the feature is intentional and that it exists. Which is why I didn’t flat out say it first.

Ok, I understand now. Thank you.