简体   繁体   English

我需要更好地理解 for 循环

[英]I need better understanding on for loops

can someone explain me how this for loop works ( Line 9 in code below ), and also if you can show me a simple example with it can be very helpfull, thank you anyways!谁能解释一下这个for 循环是如何工作的(下面代码中的第 9 行),如果你能给我看一个简单的例子,它会非常有帮助,无论如何谢谢你!

1 #include <iostream>
2 #include <cstdlib>
3 
4 using namespace std;

5 int main(){
6     int n, a , b , ma=0,mb=1000000001;
7     cin >> n ;
8     cin >> a;
9     for( n--; n ; --n ){
10         cin >> b;
11         if(abs(a-b) < abs(ma-mb))
12             ma=a , mb=b;
13         else
14             if(abs(a-b) == abs(ma-mb) && ma+mb > a+b)
15                 ma=a , mb=b;
16         a = b;
17     }
18     cout << ma << " " << mb;
19     return 0;
20 }

A for loop is simply another way to write a while loop. for 循环只是编写 while 循环的另一种方法。 So this:所以这:

for( n--; n ; --n ){
    ...
}

is the same as this:与此相同:

n--;
while(n) {
    ...
    --n;
}

Which, in this specific case, is easier to read.在这种特定情况下,哪个更容易阅读。 First it decrements n , then does the loop, decrementing n again at the end of each loop, until that decrement causes n to evaluate to false by becoming 0 .首先它递减n ,然后执行循环,在每个循环结束时再次递减n ,直到该递减导致n通过变为0评估为false

This code smells a lot.这段代码闻起来很臭。 If you give to n the value 10,it gives如果你给n值 10,它给出

9 (first time into loop, exectues n-- ) every other iteration it executes --n till when n!=0 (which is the condition n 9(第一次进入循环,执行n-- )它执行的每隔一次迭代--n直到 n!=0 时(这是条件n

A for loop works the following way: for 循环的工作方式如下:

It runs for a certain number of times.它运行一定次数。 We signify this with a condition.我们用一个条件来表示这一点。 It has a start and an increment:它有一个开始和一个增量:

for (start ; condition ; increment )
{
// loop body
}

For loops and all loops are very useful when you want to perform repetitive tasks.当您想执行重复性任务时,for 循环和 all 循环非常有用。

Lets say that you want to make a game and this game will have 3 rounds.假设您想制作一款游戏,这款游戏将进行 3 轮。 Each one of those rounds can be implemented as an iteration of a for loop.这些轮次中的每一轮都可以实现为 for 循环的迭代。 It will look like this:它看起来像这样:

for(int round = 0; round < 3; ++round) {
// game round logic
}

In the above loop we start at 0. Once we reach 3, we would have already executed the for-loop 3 times.在上面的循环中,我们从 0 开始。一旦达到 3,我们就已经执行了 3 次 for 循环。 After each iteration of the for loop ++round gets executed, this increments the variable round by 1. We can increment it by a different value by doing: round+=2 or round*=2 etc.在 for 循环 ++round 的每次迭代被执行后,这会将变量 round 递增 1。我们可以通过执行以下操作将其递增不同的值:round+=2 或 round*=2 等。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM