2017-10-20 31 views
1

這是爲歐拉19.我幾乎想出了代碼,但由於某種原因,我的輸出是+1。歐拉19輸出

#include <stdio.h> 

#define SIZE 12 

    int main(void) 
    { 
      int year; 
      int month; 
      int daysinmonths[SIZE] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; 
      int currentday = 365; /* Account for 1900 */ 
      int sundaycount = 0; 

     for (year = 1901; year <= 2000; year++) { 
       if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) { 
         daysinmonths[1] = 29; 
       } 
       for (month = 0; month < SIZE; month++) { 
         if (currentday % 7 == 0) 
           sundaycount++; 
         currentday += daysinmonths[month]; 
       } 
     } 
     printf("%d Sundays as the first of a month from 1901 to 2000 \n", sundaycount); 
    } 
+0

如果你所描述的歐拉19,節省大家搜索這將是很好。另外「我的輸出是+1」是什麼意思? –

+0

輸出應該是171,但我得到172,因此+1。 Euler 19要求我們找出從1901年到2000年這個月的第一個星期幾是多少。 – kamisama

+3

第一次遇到閏年時,您將二月份的天數設置爲29.您將它重新設置爲28? –

回答

0
#include <stdio.h> 

#define SIZE 12 

    int main(void) 
    { 
      int year; 
      int month; 
      int daysinmonths[SIZE] = {31, 28, 31, 30, 31, 30, 31, 31, 30, 31, 30, 31}; 
      int currentday = 366; /* Account for 1900 */ 
      int sundaycount = 0; 

     for (year = 1901; year <= 2000; year++) { 
       if ((year % 4 == 0 && year % 100 != 0) || year % 400 == 0) { 
         daysinmonths[1] = 29; 
       } 
       else{ 
        daysinmonths[1] = 28; 
       } 
       for (month = 0; month < SIZE; month++) { 
         if (currentday % 7 == 0){ 
           sundaycount++; 
         } 
         currentday += daysinmonths[month]; 
       } 
     } 
     printf("%d Sundays as the first of a month from 1901 to 2000 \n", sundaycount); 
    } 
+1

謝謝!這解決了這個問題。好像我應該把第一天分配給366. – kamisama

+0

好吧,歡迎你 –

+0

我認爲是對的。 1900年不是閏年,但1900年1月1日是星期一,而不是星期天。即1899年12月31日是星期天。添加365到那個,你有1900年12月31日。添加366到你想要的1901年1月1日。 –