初学者,问题或许很傻1 public class wanshu
  2 {public static void main(String args[])
  3     {int a,b,c;
  4     for(a=2;a<=10000;a++)
  5         {c=0;
  6         for(b=1;b<a;b++)
  7             {if(a%b==0)
  8             c+=b;
  9             }
 10         if(c==a)
 11             {System.out.println(a);
 12             }
 13         }
 14     }
 15 }
如上:是一个求完数的程序,可以正常编译输出结果。
完数:一个数如果恰好等于除它本身外的因子之和,这个数就称为"完数"。例如6=1+2+3.(6的因子是1,2,3)
下面的为什么编译通过,而无法输出结果?
  1 public class wanshu
  2 {public static void main(String args[])
  3     {int a,b,c=0;
  4     for(a=2;a<=10000;a++)
  5         {
  6         for(b=1;b<a;b++)
  7             {if(a%b==0)
  8             c+=b;
  9             }
 10         if(c==a)
 11             {System.out.println(a);
 12             }
 13         }
 14     }
 15 }
    

解决方案 »

  1.   

    In procedure 1: every time run:for(a=2;a <=10000;a++) , "c" is initialized to "0"But in procedure 2: every time run:for(a=2;a <=10000;a++), "c" equals another value.
    The most reason is that "c" is a global variable.
      

  2.   

    第一个程序中每次执行for循环c都重新赋值为0了,第二个程序你的c初始为0,以后每次循环都在变
      

  3.   

    作用域的問題 
      3    {int a,b,c; 
      4    for(a=2;a <=10000;a++) 
      5        {c=0; 

      1 public class wanshu 
      2 {public static void main(String args[]) 
      3    {int a,b,c=0; 
    是不同的作用域吧 LZ你在仔細想想。
      

  4.   

    刚学JAVA,有点生疏,现在已经理解了,多谢大家