4

我尝试使用Zeller's Congruence编写代码以查找给定日期的星期几,但我没有得到正确的输出。我的代码有什么问题?

#include <stdio.h>
#include <math.h>
int main()
{
  int h,q,m,k,j,day,month,year;
  printf("Enter the date (dd/mm/yyyy)\n");
  scanf("%i/%i/%i",&day,&month,&year);
  if(month == 1)
  {
    month = 13;
    year--;
  }
  if (month == 2)
  {
    month = 14;
    year--;
  }
  q = day;
  m = month;
  k = year % 100;
  j = year / 100;
  h = q + floor(13/5*(m+1)) + k + floor(k/4) +  floor(j/4) + 5 * j;
  h = h % 7;
  switch(h)
  {
    case 0 : printf("Saturday.\n"); break;
    case 1 : printf("Sunday.\n"); break;
    case 2 : printf("Monday. \n"); break;
    case 3 : printf("Tuesday. \n"); break;
    case 4 : printf("Wednesday. \n"); break;
    case 5 : printf("Thurday. \n"); break;
    case 6 : printf("Friday. \n"); break;
  }
  return 0;
}
4

2 回答 2

3

这是一个工作版本:

#include <stdio.h>
#include <math.h>
int main()
{
  int h,q,m,k,j,day,month,year;
  printf("Enter the date (dd/mm/yyyy)\n");
  scanf("%i/%i/%i",&day,&month,&year);
  if(month == 1)
  {
    month = 13;
    year--;
  }
  if (month == 2)
  {
    month = 14;
    year--;
  }
  q = day;
  m = month;
  k = year % 100;
  j = year / 100;
  h = q + 13*(m+1)/5 + k + k/4 + j/4 + 5*j;
  h = h % 7;
  switch(h)
  {
    case 0 : printf("Saturday.\n"); break;
    case 1 : printf("Sunday.\n"); break;
    case 2 : printf("Monday. \n"); break;
    case 3 : printf("Tuesday. \n"); break;
    case 4 : printf("Wednesday. \n"); break;
    case 5 : printf("Thurday. \n"); break;
    case 6 : printf("Friday. \n"); break;
  }
  return 0;
}

现场演示

关键是在你的h公式中:13/5*(m+1). 这是使用整数除法,它13/5首先计算,所以结果等价于2*(m+1)。左右交换,5结果(m+1)将是正确的。

顺便说一句,如果 1 月/2 月,您确实需要减少年份,正如 wiki 文章所解释的那样。

于 2013-02-28T04:57:58.577 回答
0

为什么要包括“h= year % 100”和“j= year / 100”??????

#include <stdio.h>
#include <math.h>
int main()
{
  int h,q,m,k,j,day,month,year;
  printf("Enter the date (dd/mm/yyyy)\n");
  scanf("%i/%i/%i",&day,&month,&year);
  if(month == 1)
  {
    month = 13;
    year--;
  }
  if (month == 2)
  {
    month = 14;
    year--;
  }
  q = day;
  m = month;
  k = year % 100;
  j = year / 100;
  h = q + 13*(m+1)/5 + k + k/4 + j/4 + 5*j;
  h = h % 7;
  switch(h)
  {
    case 0 : printf("Saturday.\n"); break;
    case 1 : printf("Sunday.\n"); break;
    case 2 : printf("Monday. \n"); break;
    case 3 : printf("Tuesday. \n"); break;
    case 4 : printf("Wednesday. \n"); break;
    case 5 : printf("Thurday. \n"); break;
    case 6 : printf("Friday. \n"); break;
  }
  return 0;
}
于 2016-12-13T12:29:29.900 回答