while循环出现的问题

时间:2023-03-10 04:08:16
while循环出现的问题

 1         int c = 0;
intg = c%2;
while(c<=100)
  {  
5
6 if(g == 1)
7 {
8 System.out.println(c);
9 }
c++;
}

自己看了很久没看出来,后来请教同学才知道,变量g是不能写在一开始的,因为while循环只是循环自己的那个花括号内的指令,不会循环外面的,这样变量g就不会做出改变了,变成了一个没有意义的数据,后来更改了一下就可以正常输出了,改为:

         int c = 0;
int g;
while(c<=100)
{
g = c%2;
if(g == 1)
{
System.out.println(c);
}
c++;
}

这样才是可以运行的代码!