"for" 使用减号时添加循环,使用加号时减去循环

"for" loop added when I use minus and subtracted when I use plus

为什么当我在内循环中 for loop 中加 1 时它减去一个值,而当我写 - 1 时它增加了一个值?

#include <stdio.h>
#include <cs50.h>

int main(void)
{
    //assignment name "height" to data type "integer"
    int height; 
    //сheck that the player has entered height from 1 to 8
    do 
    {
        height = get_int("Height:");
    }
    while (height < 1 || height > 8);
    // print columns according to the number seted by player
    for (int colums = 0; colums < height; colums++)
    {
        printf("#");

        //print rows according to the number seted by player minus one row   
            for (int rows = colums + 1; rows < height; rows++)
            {
                printf("@");
            }
        printf("\n");
    }
}

输出为:

Height:4    
#@@@
#@@
#@
#

here's screenshot

现在我将值从 for(rows = colums + 1;...) 更改为 for(rows = colums - 1;...)

#include <stdio.h>
#include <cs50.h>

int main(void)
{
    //assignment name "height" to data type "integer"
    int height; 
    //сheck that the player has entered height from 1 to 8
    do 
    {
        height = get_int("Height:");
    }
    while (height < 1 || height > 8);
    // print columns according to the number seted by player
    for (int colums = 0; colums < height; colums++)
    {
        printf("#");

        //print rows according to the number seted by player minus one row   
            for (int rows = colums - 1; rows < height; rows++)
            {
                printf("@");
            }
        printf("\n");
    }
}

输出为:

Height:4
#@@@@@
#@@@@
#@@@
#@@

here's screenshot

所以情况就是这样一个循环:

for (rows = columns + 1; rows < height; rows++) {
     // do something
}

我想你是在问为什么当循环说 for (rows = columns + 1;... 时循环执行的次数比它说 for (rows = columns - 1;... 时要少。原因是 for 循环的第一部分是初始条件;这是你给 rows 初始值的地方。如果您将 add 1 添加到起始值,然后将 up 计数到某个最终值(在本例中为 height),那么您已经减少 起始值和最终值之间的差异。

考虑一下:

height = 3;
for (rows = 1; rows < height; rows++) {...}

与此相对:

height = 3;
for (rows = -1; rows < height; rows++) {...}

您认为这些循环中的哪一个会执行更多次?

当您使用时,

for(int row = column+1; row<height; row++)

您正在指示编译器运行 从行+1 的初始值开始循环。因此for循环少执行了一次

例如 column=3, row = 3+1 =4 , height = 6 。然后 for 循环将执行 2 次,即 for row = 4 and 5

同样

for(int row = column-1; row<height; row++)

额外执行两次

例如column=3, row = 3-1 =2, height = 6。那么for循环会执行3次,即for row = 2,3,4 and 5。