[英]Program for Date calculator in C
我正在尝试在 C 程序中编写一个日期计算器,范围从 1902 年 1 月 1 日到 2299 年 12 月 31 日,我遵循http://en.wikipedia.org/wiki_week/theCalculating_the_day_of中的算法世纪表,月表和日表,但是当我尝试打印出来时,这就是我所拥有的
Enter Year, Month and Day as YYYY,M,DD
1982 4 24
Saturday1982 ,6, 24, is 6
而不是说1982 4 24 is a Saturday
我写的程序有什么问题? 开关盒的位置?
#include <stdio.h>
int main (void)
{
// insert code here...
int day,month,year;
printf("Enter Year, Month and Day as YYYY,M,DD\n");
scanf("%4d%d%2d", &year, &month, &day);
if (year >= 1901 && year <= 2299 &&
month >= 1 && month <= 12 &&
day >= 0 && day <= 31)
{
int century = year/100;
/* making a century table for calculation*/
switch(century)
{
case 19:
century=0;
break;
case 20:
century=6;
break;
case 21:
century=4;
break;
case 22:
century=2;
break;
}
int last2_of_year= year % 100;
/* Last 2 digits of the year entered*/
int last2_div_4 = last2_of_year/4;
switch (month)
{
case 1:
month=0;
break;
case 2:
month=3;
break;
case 3:
month=3;
break;
case 4:
month=6;
break;
case 5:
month=1;
break;
case 6:
month=4;
break;
case 7:
month=6;
break;
case 8:
month=2;
break;
case 9:
month=5;
break;
case 10:
month=0;
break;
case 11:
month=3;
break;
case 12:
month=5;
break;
}
int total_num = (century+ last2_of_year +day +month +last2_div_4)%7;
switch (total_num)
{
case 0:
printf("Sunday");
break;
case 1:
printf("Monday");
break;
case 2:
printf("Tuesday");
break;
case 3:
printf("Wednesday");
break;
case 4:
printf("Thursday");
break;
case 5:
printf("Friday");
break;
case 6:
printf("Saturday");
break;
}
printf("%d ,%d, %d, is a %d", year,month,day,total_num);
}
else
{
printf("invalid\n");
}
return 0;
}
你说:
printf("%d ,%d, %d, is a %d", year,month,day,total_num);
这是要打印的
L, M, N, is a P
其中L
、 M
、 N
和P
是数字。
您需要在日期名称switch
之前使用printf()
,并且需要从printf
中删除最后的%d
和total_num
。 然后printf
将打印
L, M, N, is a
并且日期名称switch
中的printf
将在同一行打印出当天的名称,给你
L, M, N, is a XXXXXXXXXXX
编辑地址评论:
查看您的程序中的 output 语句。
遇到的第一个 output 语句是打印出日期名称的日期名称开关中的printf
调用。 因此,当您的程序根据您提到的输入运行时,将打印出的第一件事是
Saturday
然后在日期名称切换之后,下一个printf
是
printf("%d ,%d, %d, is a %d", year,month,day,total_num);
由于year
是1982
, month
是4
, day
是24
, total_num
是6
,所以printf
将 output
1982, 4, 24, is a 6
与上Saturday
output在同一行,也就是说整个output是
Saturday1982, 4, 24, is a 6
看起来@QuantumMechanic 找到了问题的根本原因,但我想建议一些更改:
int century = year/100;
/* making a century table for calculation*/
switch(century)
{
case 19:
century=0;
break;
我对使用单个变量来表示两种不同的事物持怀疑态度。 在这里, century
既代表用户输入的人类可读世纪,又代表该世纪一周的第一天的偏移量。 如果需要,两个变量将提供更清晰的代码,并允许您在以后重新使用century
信息。
其次,使用case
语句来存储几个月的偏移量感觉有点……过头了:
switch (month)
{
case 1:
month=0;
break;
case 2:
month=3;
break;
case 3:
month=3;
break;
这可以通过数组查找来处理:
int leap_month[] = [-1, 6, 2, 3, 6, 1, 4, 6, 2, 5, 0, 3, 5];
int norm_month[] = [-1, 0, 3, 3, 6, 1, 4, 6, 2, 5, 0, 3, 5];
if (leap_year)
month_offset = leap_month[month];
else
month_offset = norm_month[month];
-1
只是为了允许引用具有人类友好索引的表( Jan == 1
)。 如果您觉得更容易,请随意删除它并使用leap_month[month-1]
或类似的。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.