问答详情
源自:4-8 Java循环语句之 do...while

求大神指点下这个算法结果为啥不对?结果为62

public class dp {

public static void main(String[] args){

int num = 2;     

do {

//实现累加求和    

            num+=num;

num = num + 2;           

} while (num<=50);        

System.out.println(" 50以内的偶数之和为:" + num );

}

}


提问者:初心noc 2015-08-22 00:18

个回答

  • 天润
    2016-01-28 15:28:20

    public static void main(String[] args) {

    int num = 2;

    int sum=0;

    do {

    //实现累加求和    

               sum+=num;//sum=sum+num

    num = num + 2;           

    } while (num<=50);        

    System.out.println(" 50以内的偶数之和为:" + sum );

    }

    注意num和sum的区别 

  • qq_呵呵_38
    2015-09-01 08:51:42

    public class dp {

    public static void main(String[] args){

    int num = 2;     

    do {

    //实现累加求和    

                num+=num;         //这句应该是   sum+=num;    sum才是总和!

    num = num + 2;           

    } while (num<=50);        

    System.out.println(" 50以内的偶数之和为:" + num );

    }

    }


  • 糖菲果
    2015-08-22 01:17:46

    public class Test {

        public static void main(String[] args){

                int sum = 0;

                for (int i = 0; i <=50; i++) {

                    if(i%2==0){//判断是不是偶数

                    sum += i;

                }

            }       

            System.out.println("50以内的偶数之和为:" + sum );

        }

    }