且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

为什么我在减少时不能在for循环中使用'less than'运算符(<)

更新时间:2023-11-05 23:07:46

 for(int i = 1000; i< = 1; i- = 2)
for (int i = 1000; i< 1; i- = 2)







看看你的码。你开始时i< 1是假的,所以它什么都不做



当你使用> =版本时,你不会立即中止。



您需要重新考虑不等式的顺序!


首先,研究这个执行for循环的流程 [ ^ ]
如果

(int i = 1000; i



1.初始化:i初始化为1000,即i = 1000,然后进入2;

2.条件:结果i< = 1,即1000< = 1,为False,退出循环,因此

 System.out.println(i); 

将永远不会被执行。


Hi, I guess it's really silly question but:
why --> for (int i = 1000; i >=1; i-=2) System.out.println(i); (Cmd prints i)

---> for (int i = 1000; i <=1; i-=2) System.out.println(i); (no errors, no printing on the screen)

Why when i input <= cmd doesn't react and don't display decreasing iteration ?

Thank you in addvance!

What I have tried:

for (int i = 1000; i <=1; i-=2)
for (int i = 1000; i <1; i-=2)

for (int i = 1000; i <=1; i-=2)
for (int i = 1000; i <1; i-=2) 




Look at your code. You start off with i<1 being false so it does nothing

When you use the >= version, you don't abort immediately.

You need to rethink about the order for the inequality!


First, study this Flow of Execution of the for Loop[^]
in the case of
for (int i = 1000; i <=1; i-=2) System.out.println(i); 


1. Initialization: i is initialized to 1000, i.e. i=1000, then it proceeds to 2;
2. Condition: the outcome of i <= 1, i.e. 1000 <= 1, is False, exit the loop, as such

System.out.println(i);

will never be executed.