Calendar formula

I have the formula I need, however I get an error when I try to compile.

1
2
3
int day, yr;

day = ((((yr - 1) * 365) + floor((yr - 1) / 4) - floor((yr - 1) / 100) + floor((yr - 1) / 400)) + 1) % 7;


I get an error:
"error: invalid operands of types 'double' and 'int' to binary 'operator%'|"

I understand that you need an int to use %, but why isn't it working when I definitely declared an int? What can I change to make it work?
floor can only use double, float and long double.

I believe floor is converting the value into a double
How do I make the formula work, then?

I'm absolutely lost on this
you could try leaving out the modulus operator until the very end.
What i mean is:
Do all the calculations without the modulus first.
Convert that answer into an int
Do the calculation involving the modulus
So this might be of use:

1
2
3
4
5
    int day, yr;


    day = ((((yr - 1) * 365) + floor((yr - 1) / 4) - floor((yr - 1) / 100) + floor((yr - 1) / 400)) + 1);
    day = day%7;


This runs without error
Last edited on
Thank you very much, I have no problems with it now :)
There are several problems with your code. First since floor() returns a double you are mixing floating point and integer math. You don't need floor() since by design integer math truncates any fractional parts, there are no fractions in integer math. So I recommend just using integer math, but always remember that there are no fractions 2010 / 100 will yield 20, and 1 / 5 will yield zero.

Your error is being caused by the use of the floor() it makes the equation into a floating point value, and you can't use the modulus operator on floating point numbers.

1
2
// This yields a floating point number: 
((((yr - 1) * 365) + floor((yr - 1) / 4) - floor((yr - 1) / 100) + floor((yr - 1) / 400)) + 1)

Topic archived. No new replies allowed.