C &引用;至于;循环使用减号时加,使用加号时减
为什么当我在C &引用;至于;循环使用减号时加,使用加号时减,c,loops,cs50,C,Loops,Cs50,为什么当我在中为循环在内部循环中添加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
中为循环
在内部循环中添加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");
}
}
现在我已经将值从(rows=colums+1;…)的更改为(rows=colums-1;…)的
所以情况是这样的循环:
for (rows = columns + 1; rows < height; rows++) {
// do something
}
与此相比:
height = 3;
for (rows = -1; rows < height; rows++) {...}
高度=3;
对于(行=-1;行<高度;行++){…}
您认为这些循环中的哪一个会执行更多次?当您使用
for(int row = column+1; row<height; row++)
用于(int row=column+1;row当columns
为0时,-1
版本会发生什么情况?尝试手动执行循环并跟踪每个变量的值。在您的示例中,这并不太难。请将代码粘贴到中,而不是使用图片。您也可以而且应该包括您的输出。这肯定不会让人感到更舒服或更容易更容易看到代码的图像而不是实际文本。具有[-1]的版本将有更多的输出,因为它在[row=height]之前会有更多的迭代。感谢您如此易懂的解释!它将我带到了下一个级别。)
for (rows = columns + 1; rows < height; rows++) {
// do something
}
height = 3;
for (rows = 1; rows < height; rows++) {...}
height = 3;
for (rows = -1; rows < height; rows++) {...}
for(int row = column+1; row<height; row++)
for(int row = column-1; row<height; row++)