2011-11-01 60 views
0

我得到的错误是“System.ArgumentOutOfRangeException was unhandled。”它要求月份在1和12之间。但是看看调试器中的变量,它等于1以及一个Debug.Writeline。循环中的歧义?

int month, year, total; 
    total = 0; 
    DateTime dayToFind; 

    for (year = 1001; year < 1201; year++){ 
     for (month = 1; month < 12; month++){ 
      dayToFind = new DateTime(year, month, DateTime.DaysInMonth(month, year)); 
      // The error points at the last occurance of month above. 
      total = (dayToFind.DayOfWeek == DayOfWeek.Monday) ? 1 : 0; 
     } 

    } 
+1

不应该是'month = 1;月<13岁,或者你故意跳过12月? –

+0

是的,当我切换机器时,我输入的太快而不是仅仅复制和粘贴。另请注意'total ='应该是'total + ='。除非我喜欢循环而不是实际聚合。 – surfasb

回答

8

你有你的DateTime.DaysInMonth()回调。它改成这样:

DateTime.DaysInMonth(year, month) 

当你把year变量的month的地方,它是大于最大,它可以是(大于12),导致ArgumentOutOfRangeException

DateTime.DaysInMonth()

+0

Ack。去搞清楚。 – surfasb

+0

@surfasb :)它发生在我们所有人身上。没有什么比看着它的额外眼睛更好。 – 2011-11-01 20:10:30

+0

有一首歌,“我得到朋友的一点帮助......” – surfasb

2

你扭转了论据,DaysInMonth方法。年份第一。