A股上市公司传智教育(股票代码 003032)旗下技术交流社区北京昌平校区

 找回密码
 加入黑马

QQ登录

只需一步,快速开始

© 陈作亮 注册黑马   /  2012-3-16 23:04  /  1499 人查看  /  3 人回复  /   0 人收藏 转载请遵从CC协议 禁止商业使用本文

请问以下程序输出值为什么是0,public class plus { public static void main(String args[]) {int sum=0; int n=100; do { n--; } while(n>0); {sum+=n;} System.out.println("the sum of the first 100 natural number is"+sum); }}

3 个回复

倒序浏览
                do
                {
                        n--;       
                }while(n>0);
执行完 n就等于0了;
揣摩你的意思应该这么写:
                do
                {
                        sum+=n;
                        n--;
                }while(n>0);
回复 使用道具 举报
public class plus {
public static void main(String args[])
{
int sum=0; int n=100;
do { n--;sum+=n; } while(n>0);
{
System.out.println("the sum of the first 100 natural number is"+sum); }}

你的sum+=n 不在循环体内,当然输出的0啦!
回复 使用道具 举报
public class plus{
public static void main(String args[]) {
                int sum = 0;
                int n = 100;
                do {
                        n--;
                }
                while (n > 0);//当n==1时,还要去执行n--,之后,n==0,不满足条件,才执行while()后面的代码块。此时n==0了,所以结果是0
                {
                        sum += n;
                }
                System.out.println("the sum of the first 100 natural number is" + sum);
        }
}

评分

参与人数 1技术分 +1 收起 理由
房宝彬 + 1

查看全部评分

回复 使用道具 举报
您需要登录后才可以回帖 登录 | 加入黑马