【发布时间】:2019-05-16 21:05:21
【问题描述】:
我正在编写一个代码来计算 2 个给定日期之间的天数差异。请注意,每个月被视为等于 30 天,每年被视为等于 360 天。
我收到以下警告/错误,但我似乎不明白为什么:
这是我的代码:
#include <stdio.h>
int dif_days(struct Date Date1, struct Date Date2);
struct Date
{
int Day;
int Month;
int Year;
};
int main()
{
struct Date Date1;
struct Date Date2;
printf("\n Please enter the first date: ");
scanf("%d %d %d ", &Date1.Day, &Date1.Month, &Date1.Year);
printf("\n Please enter the second date: ");
scanf("%d %d %d ", &Date2.Day, &Date2.Month, &Date2.Year);
int diff = dif_days(Date1, Date2);
printf("\n The difference in days is: %d \n", diff);
return 0;
}
int dif_days(struct Date Date1, struct Date Date2)
{
// variable declaration
int difference;
int Day, Month, Year; // The final days/months/years
// for the days
if (Date1.Day > Date2.Day)
Day = Date1.Day - Date2.Day;
else
Day = Date2.Day - Date1.Day;
// for the months
if (Date1.Month > Date2.Month)
Month = Date1.Month - Date2.Month;
else
Month = Date2.Month - Date1.Month;
// for the years
if (Date1.Year > Date2.Year)
Year = Date1.Year - Date2.Year;
else
Year = Date2.Year - Date1.Year;
difference = Day + Month*30 + Year*360;
return difference;
}
【问题讨论】:
-
您的原型定义
int dif_days(struct Date Date1, struct Date Date2);使用了此时未定义的结构数据。所以把它移到struct Date的定义之后。除此之外,您的计算错误的方式很多;你用“16 12 2018”和“16 12 2018”测试了吗? “2018 年 31 月 12 日”和“2019 年 1 月 1 日”? -
@KlausGütter 我已经将结构 Date 移到原型定义上。我尝试测试“16 12 2018”和“16 12 2018”,结果为零。但是,您向我推荐的其他组合似乎没有给出有效答案,因此我将再次查看我的算法。感谢您指出!
-
@KlausGütter 我设法重新编写了代码,现在它就像一个魅力,但仍然存在一个小问题。如果用户输入“31 12 2018”和“1 1 2019”,答案是 0。我是否应该在我的函数中添加一个 if 语句来检查用户是否输入了超过 30 天,以便他们可以转换为30 因为这是变量
day可以拥有的最大值。 -
为什么不计算
360*year + 30*month + day这两天的差额? -
@KlausGütter 这就是我所做的。我分别计算了每个日期的天数,然后我做了一个
if这样的声明:if (days_of_date1 > days_of_date2) difference = days_of_date1 - days_of_date2; else difference = days_of_date2 - days_of_date1;