Reputation: 11
I'm new to C-programming and I'm trying to make a code to count the day difference between a date and a birthday.
int year, birth_year;
int year_common;
int year_leap;
for(int i = year; i <= birth_year; i--){
year = i;
if (year % 400 != 0 || (year % 100 == 0 && year % 400 != 0)){
year_common++;
}
if(year % 400 == 0 || (year % 100 != 0 && year % 4 == 0)){
year_leap++;
}
}
int date_pass = (year_common * 365) + (year_leap * 366);
I wanted the loop to decrement the 'i', add 1 into the year_common integer when it's a common year, and add 1 into the year_leap integer when it's a leap year until it is the same as the birth_year.
For now, I'm still trying to check out the years, but no matter how many year difference I made, they always give out 5856 days.
e.g. : birth date : 05/11/2005 checked date : 05/11/ 2007 give out '5856 days'
And I don't know where that number comes from.
I tried initializing it with 0, but it gave out 0 days instead.
I tried this code:
int year_pass = year - birth_year;
int year_leap = 0;
for(int i = year; i <= birth_year; i--){
if(i % 400 == 0 || (i % 100 != 0 && i % 4 == 0)){
year_leap++;
}
}
int date_pass = (year_pass * 365) + (year_leap * 1);
And it missed 1 day for the leap year.
Is there something wrong with the loop?
My prof wants the code to be as standard as possible with loops and conditions.
Upvotes: 0
Views: 96
Reputation: 95
You have declared the year common and year leap as in variables but haven't assigned any value. Since youre adding one unit by ++;
, you need to pre define year_leap and year_common =0
int year, birth_year;
int year_common=0;
int year_leap=0;
Upvotes: 1
Reputation: 141593
Dates are hard to handle, with all UTC leap seconds and local timezones - leap years are only the tip of the iceberg. Don't reinvent the wheel. Whenever you want to do something with dates, first thing to do is to convert everything to seconds since epoch. Then you do what you want.
#include <time.h>
#include <stdio.h>
#include <stdint.h>
int main() {
// 05/11/2005
struct tm birthday = {
.tm_year = 2005 - 1900,
.tm_mon = 11,
.tm_mday = 5,
.tm_hour = 12,
};
// 05/11/2007
struct tm end = {
.tm_year = 2007 - 1900,
.tm_mon = 11,
.tm_mday = 5,
.tm_hour = 12,
};
time_t birth_s = mktime(&birthday);
time_t end_s = mktime(&end);
time_t diff_s = end_s - birth_s;
time_t diff_day = diff_s / 3600 / 24;
printf("%ju\n", (uintmax_t)diff_day);
}
Upvotes: 0