马上注册,结交更多好友,享用更多功能^_^
您需要 登录 才可以下载或查看,没有账号?立即注册
x
计算出来的天数不正确,请问哪里出了问题?#include <stdio.h>
#include <time.h>
void leap_years(int time_s,int *leap)
{
int day_remainder = (time_s % (3 * 365 * 86400 + 366 * 86400)) / 86400;//get the remainder day of four year
if (day_remainder >= 0 && day_remainder < 365)
{
*leap = 0;
}
else if (day_remainder >= 365 && day_remainder < (365 * 2))
{
*leap = 1;
}
else if (day_remainder >= (365 * 2) && day_remainder < (365 * 2 + 366))
{
*leap = 2;
}
else
{
*leap = 3;
}
}
void cal_second_remainder(int time_s,int *second_remainder)
{
int leap;
leap_years(time_s,&leap);
switch(leap)
{
case 0:*second_remainder = time_s % (3 * 365 * 86400 + 366 * 86400);break;
case 1:*second_remainder = time_s % (3 * 365 * 86400 + 366 * 86400) - 365 * 86400;break;
case 2:*second_remainder = time_s % (3 * 365 * 86400 + 366 * 86400) - 365 * 2 * 86400;break;
case 3:*second_remainder = time_s % (3 * 365 * 86400 + 366 * 86400) - (365 * 2 + 366) * 86400;break;
}
}
void calculate_year(int time_s,int *year)
{
int leap;
leap_years(time_s,&leap);
*year = 4 * (time_s / (3 * 365 * 86400 + 366 * 86400)) + 1970 + leap;
}
void calculate_day(int time_s,int *day)
{
int second_remainder;
cal_second_remainder(time_s,&second_remainder);
*day = second_remainder / 24 * 60 * 60;
}
void calculate_hour_minute(int time_s,int *hour,int *minute)
{
int day,second_remainder,leap,second;
calculate_day(time_s,&day);
cal_second_remainder(time_s,&second_remainder);
second = second_remainder - day * 24 * 60 * 60;
*hour = second / 60 * 60;
*minute = second / 60;
}
int main()
{
int time_s = time(NULL);
int year,day,hour,minute;
calculate_year(time_s,&year);
calculate_day(time_s,&day);
calculate_hour_minute(time_s,&hour,&minute);
printf("senconds:%i\n",time_s);
printf("year:%i\n",year);
printf("day:%i\n",day);
printf("hour:%i\n",hour);
printf("minute:%i\n",minute);
return 0;
}
计算天数的代码中有几个地方出了问题。
1. 在函数`calculate_day`中,计算天数的公式应该是除以86400而不是乘以86400。 *day = second_remainder / (24 * 60 * 60);
2. 在函数`calculate_hour_minute`中,计算小时和分钟的公式也出错了。应该用取余操作符`%`而不是整除操作符`/`。 *hour = second / (60 * 60);*minute = (second % (60 * 60)) / 60;
修改以上两处错误后,你的代码应该可以正确计算出天数、小时和分钟了。
以上回复来自 -- ChatGPT(FishC官方接口),如未能正确解答您的问题,请继续追问。
|