Topic: 菜鸟再提问~

  Print this page

1.菜鸟再提问~ Copy to clipboard
Posted by: aiff
Posted on: 2004-09-11 11:01

怎么算结果是210呢?我算的是190

public class Cc
{
public static void main(String args[])
{
int limit=20,
sum=0,
i=1;
while
(i<limit)
sum+=i++;
System.out.print("sum="+sum);
}}

2.Re:菜鸟再提问~ [Re: aiff] Copy to clipboard
Posted by: why
Posted on: 2004-09-11 11:20

If you don't know how to use a debugger to trace what happened, print the intermediate results:

public class Cc
{

public static void main(String args[])
{
int limit=20,
sum=0,
i=1;
while (i<limit) {
System.out.println("i=" + i + "; sum="+sum);
sum+=i++;
}
System.out.print("sum="+sum);
}

}

Well, 1+2+...+19 = 19 * (19+1) / 2 = 190, what's wrong?

3.Re:菜鸟再提问~ [Re: aiff] Copy to clipboard
Posted by: aiff
Posted on: 2004-09-11 12:39

good method~3q

4.Re:菜鸟再提问~ [Re: aiff] Copy to clipboard
Posted by: alpacino
Posted on: 2004-09-23 16:37

循环尽量用FOR,这种写法你不头痛吗?
class Add
{
public static void main(String args[])
{
int limit=20,sum=0;
for(int i=1;i<limit;i++)
{
sum+=i;
System.out.println("i="+i+"\t"+"sum="+sum);
}
}
}

5.Re:菜鸟再提问~ [Re: aiff] Copy to clipboard
Posted by: shuikun
Posted on: 2004-09-23 19:39

我运行的结果是190呀,你再试一次吧,不过说句实在话,你这种写程序的方式,我不敢恭维,


   Powered by Jute Powerful Forum® Version Jute 1.5.6 Ent
Copyright © 2002-2021 Cjsdn Team. All Righits Reserved. 闽ICP备05005120号-1
客服电话 18559299278    客服信箱 714923@qq.com    客服QQ 714923