【问题标题】:"for" loop added when I use minus and subtracted when I use plus“for”循环在我使用减号时添加,在我使用加号时减去
【发布时间】:2020-06-07 05:38:49
【问题描述】:

为什么当我在内循环中在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

【问题讨论】:

  • 当columns 为0 时,-1 版本会发生什么?尝试手动执行循环并遵循每个变量的值。在您的示例中并不太难
  • 请粘贴您的代码而不是使用图片。您也可以而且应该包括您的输出。以任何方式查看代码图像而不是实际文本肯定不会更舒服或更容易。

标签: c loops cs50


【解决方案1】:

当你使用时,

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

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

例如 column=3, row = 3+1 =4 , height = 6 . 那么 for 循环会执行 2 次,即 for row = 4 和 5

同样

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

会额外执行两次。

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

【讨论】:

    【解决方案2】:

    所以情况是这样的循环:

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

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

    考虑一下:

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

    相对于这个:

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

    您认为哪一个循环会执行更多次?

    【讨论】:

    • 带有 [-1] 的版本将有更多的输出,因为它在 [row = height] 之前会有更多的迭代。谢谢你这么容易理解的解释!它让我进入了一个新的水平))
    猜你喜欢
    • 2022-09-30
    • 2021-12-24
    • 2016-12-24
    • 2017-02-02
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2011-06-25
    相关资源
    最近更新 更多