PDA

View Full Version : I am getting incorrect output for data calc.


Devaspora
10-30-2009, 07:50 AM
if (mm>=4 && yyyy>=2008 || yyyy>=2008)
{
numdays=(((yyyy-2008+1)-1)*365+((yyyy-2008+1)-1)/4-((yyyy-2008+1)-1)/100+((yyyy-2008+1)-1)/400)-90; //the changes forumla to calcuate number of days between 04/01/2008 and 12/31/(yyyy-1)

switch (mm)
{
case 1: numdays+=0;
break;
case 2: numdays+=31;
break;
case 3: numdays+=59;
break;
case 4: numdays+=90;
break;
case 5: numdays+=120;
break;
case 6: numdays+=151;
break;
case 7: numdays+=181;
break;
case 8: numdays+=212;
break;
case 9: numdays+=243;
break;
case 10: numdays+=273;
break;
case 11: numdays+=304;
break;
case 12: numdays+=334;
break;
}

numdays+=dd;
nummonths=numdays/31;
numhours=numdays*24;
nummins=numhours*60;
numsecs=nummins*60;

This code will give you the amount of days, months, etc. from April 1st, 2008 but I get wrong numbers. When I put in 9 27 2009: My months output as 16 (when the should be 18) and days as 514 (when they should be 567 days if 18*30+27 is calculated)...I can't figure it out at all. Could someone help me?

Devaspora
10-30-2009, 02:36 PM
Anybody? I need to finish up this program

tomws
10-30-2009, 04:45 PM
A good way to solve this is by writing out the numdays equation with real numbers (like your example date):

((2009-2008+1)-1)*365
+ ((2009-2008+1)-1)/4
+ ((2009-2008+1)-1)/100
+ ((2009-2008+1)-1)/400
- 90

---or, assuming integers---
365
+ 0
+ 0
+ 0
- 90
====
275

---plus the value from switch---
275
+243
====
518

---plus the days---
518
+ 27
====
545


is not the 514 you mention as the return value, and it's not what you incorrectly claim it should be (567). Using 30 days to estimate the number of days is just that: an estimate. The date difference is actually 544 days.

The number you list for months is also incorrect. It's not 18 months. This is trivially easy to discover by counting on your fingers. The correct answer is 17.

No idea where your 514 number is coming from. Maybe you're doing something to the inputs before this section of code? Or to the stored values after this section?


Side notes:
Your method for calculating the number of months is flawed, even though it will return the correct integer in this case. It would be better to loop and count the months or include a counter in the current switch. A generic 30/31 division can get close, but it's easy enough to count the months separately.

Your days equation has some unnecessary computation. You're adding 1 inside parens and then immediately subtracting 1 from the result. That serves no purpose.

Devaspora
10-30-2009, 04:57 PM
Hmm, I am going to have to test out this method. Thank you