【发布时间】: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
#@@@
#@@
#@
#
现在我将值从 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
#@@@@@
#@@@@
#@@@
#@@
【问题讨论】:
-
当
columns为0 时,-1版本会发生什么?尝试手动执行循环并遵循每个变量的值。在您的示例中并不太难 -
请粘贴您的代码而不是使用图片。您也可以而且应该包括您的输出。以任何方式查看代码图像而不是实际文本肯定不会更舒服或更容易。