我正在尝试用C语言编写一个日期计算器,范围从1/1/1902到12/31/2299,我遵循了http://en.wikipedia.org/wiki/Calculating_the_day_of_the_week的算法,使用了世纪表、月表和日表,但当我试图打印出来时,我得到了以下结果
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;
}发布于 2011-05-24 08:34:40
看起来@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]或类似的工具。
发布于 2011-05-24 08:21:48
你可以说:
printf("%d ,%d, %d, is a %d", year,month,day,total_num);这将会被打印出来
L, M, N, is a P其中L、M、N和P是数字。
您需要该printf() ,然后才能使用-of-days switch,并且需要从printf中删除最终的%d和total_num。然后该printf将打印出来
L, M, N, is a而name- of -days switch中的printfs将在同一行上打印出日期的名称,给出
L, M, N, is a XXXXXXXXXXX编辑后的地址注释:
查看您的程序中的输出语句。
遇到的第一个output语句是输出日期名称的name-of-days开关中的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将输出
1982, 4, 24, is a 6与前面的Saturday输出在同一行上,这意味着整个输出是
Saturday1982, 4, 24, is a 6https://stackoverflow.com/questions/6104505
复制相似问题