【问题标题】:PROJECT EULER #19 in CC 中的 PROJECT EULER #19
【发布时间】:2014-12-09 17:37:27
【问题描述】:

我在项目 euler 上尝试了问题 19。答案是 171,但我的代码给出了 1199,这与预期的答案相差甚远。有人可以告诉我哪里出错了吗? -- 问题链接在这里:https://projecteuler.net/problem=19

#include<stdio.h>
int main()
{
    int count=2;
    int flag1=0;
    int flag2=0;
    int month=1;
    int day=1;
    int year=1901;
    int sunday=0;//count sundays

    while(1)
    {

        //check for leapyears
        if(year%4)
        {
            if((year%100==0 && year%400==0) || year%100!=0)
                flag2=1;
        }

        //update months(31days)
        if((month==1 ||month==3 || month==5 || month==7 || month==8 || month==10|| month==12) && day==31) 
        {
            flag1=1;
            day=1;
            month++;
            if(month==13)
            {
                month=1;
                year++;
                flag2=0;
            }
        }
        //update months(30days)
        if((month==4 || month==6 || month==9 || month==11) &&  day==30)
        {
            flag1=1;
            day=1;
            month++;
        }
        //update month:february
        if(month==2)
        { 
            if((flag2==0 && day==28) || (flag2==1 && day==29))    
            {
                flag1=1;
                day=1;
                month=3;
            }      
        }

        //check sunday of every month
        if(count%7==0 && flag1==1)
        {
            sunday++;
            flag1=0;
        }

        count++;

    day++;        

        if(year==2001)
            break;
    }
    printf("%d\n",sunday);

    return 0;
}

【问题讨论】:

  • 到目前为止你是如何调试它的?
  • if(year%4) 从来都不是闰年,所以随后的世纪测试无济于事。
  • leap = year%4==0 &amp;&amp; (year%100!=0 || year%400==0);
  • 你知道关于 SO 的问题必须是独立的吗?

标签: c


【解决方案1】:

错了三件事。

  • 检查闰年if(year%4) 必须是 if (year%4==0)
  • 更新月份:当您从一个月的最后一天到下个月的第一天时,您忘记增加日期count
  • 检查每个月的星期日:在遇到星期日之前,您不会重置 flag1,即使那不是在每月的第一天。

后两个错误可以改正如下:

        count += flag1; // account for extra day step
        if (count%7==0 && flag1) sunday++;
        flag1 = 0;      // reset `first of month` flag for this month

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2015-01-23
    • 1970-01-01
    • 1970-01-01
    • 2023-03-21
    • 2010-09-27
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多