public class TotalDay{
public static void main(String args[]){
int year=2001,month,day=26;
int [] MonthDay={0,31,28,31,30,31,30,31,31,30,31,30};
int total;
for(month=1;month<=12;month++){
total=0;
total+=26;
for(int m=1;m<=month-1;m++)
total+=MonthDay[m];
System.out.print("year="+year);
System.out.print("month="+month);
System.out.print("Day="+day);
System.out.println("Total="+total);
}
}
}
这段程序输出2001年每月的第26天为这一年的第几天,程序for(int m = 1;m <= month-1;m++)这句想不明白,month为月份一共12个月,为什么m=1;m<=month-1??这不就是11个月了么?可是这样打出来的结果是12个月的而用m<=month这样却是11个月为什么??

解决方案 »

  1.   

    你的12个月是跟这个有关的吧for(month=1;month<=12;month++)
    m<=month之后抛异常了,当然只有前面11个月了,真不知道楼主是怎么问问题的
      

  2.   

    for(month=1;month<=12;month++)输出的确实是12个月System.out.print("month="+month);这句,for(int m=1;m<=month;m++)这么写这12个月输出还有11个月,month-1输出12个月完整的,虽然m<=month抛异常可是程序也是输出来的呀,不过少一个月...
      

  3.   

    我想知道为什么换成m<=month之后这12个月却只输出11个月
      

  4.   

    public class TotalDay{
    public static void main(String args[]){
    int year=2001,month,day=26;
    int [] MonthDay={0,31,28,31,30,31,30,31,31,30,31,30};
    int total;
    for(month=1;month<=12;month++){
    total=0;
    total+=26;
    for(int m=1;m<=month-1;m++)
    /*这里用month-1,实际上还是输出了12次,原因很简单,因为最外面的循环是12次嘛
    但是如果使用了month,就像上面讲的,会出现数组边界溢出的问题。这个时候程序在这里报错,并终止运行,那么就少了最后一次的输出了。如果不明白就在MonthDay中再随便加一个数字出来,那就可以输出12次了,只不过是错的而已。*/
    total+=MonthDay[m];
    System.out.print("year="+year);
    System.out.print("month="+month);
    System.out.print("Day="+day);
    System.out.println("Total="+total);
    }
    }
    }