诗竹白芍 发表于 2018-11-28 14:05:58

这题万年历为什么输出了这样的结果

#include<stdio.h>
int fact1(int years, int month);
int fact2(int years, int month);
int fact3(int years, int month);
int main()
{
      int years, month,num2,num3,i,j;
      scanf_s("%d %d", &years,&month);
      num2 = fact2(years, month);
      num3= fact3(years, month);
      printf("\n日\t一\t二\t三\t四\t五\t六\t\n");
      for (i = 1;i <= num2;i++)
      {
                printf("\t");
      }
      for (j = 1;j <= num3;j++)
      {
                printf("%d\t", j);
                if ((j + num2) % 7 == 0)
                {
                        printf("\n");
                }
      }
      printf("\n");
      system("pause");
      return 0;
}
int fact1(int years, int month)
{
      int num1;
      num1 = 0;
      switch (month - 1)
      {
      case 4:case 6:case 9:case 11:
                num1 += 31;break;
      case 1:case 3:case 5:case 7:case 8:case 10:case 12:
                num1 += 30;break;
      case 2:
      {
                if (years % 4 == 0 && years % 100 == 0 || years % 400 == 0)
                {
                        num1 += 29;
                }
                else
                {
                        num1 += 28;
                }
                break;
      }
      return num1;
      }
}
      int fact2(int years,int month)
{
      int s, num2;
      s = years - 1 + (years - 1) / 4 - (years - 1) / 100 + (years - 1) / 400 + fact1(years, month) + 1;
      num2 = s % 7;
      return num2;
}
int fact3(int years, int month)
{
      int num3;
      switch (month)
      {
      case 4:case 6:case 9:case 11:num3 = 31;break;
      case 1:case 3:case 5:case 7:case 8:case 10:case 12:num3 = 30;break;
      case 2:
      {
                if (years % 4 == 0 && years % 100 == 0 || years % 400 == 0)
                {
                        num3 = 29;
                }
                else
                {
                        num3 = 28;
                }
                break;
      }
      return num3;
      }
}
代码如下,这直接就没转进去函数,不知道为什么。

KAKUI丶 发表于 2018-11-29 10:13:01

因为当你输入month为1时,你fact1中swtich(month-1),month的值为0,case找不到,就开始无限循环了
然后,看了下程序,很多地方需要修改的,例如判断大小月,大月31天,小月30天;打印中7天一个\n,你的是(j+num2)%7,这里会溢出,达不到想要的效果,可能会在7天内提前就空格了;
判断2月(闰年/平年)直接赋值29/28就好,不用+=了,增加了运算复杂度;再一个是考虑边界值的问题,year如果为1,你这个程序就崩溃了
页: [1]
查看完整版本: 这题万年历为什么输出了这样的结果