C-我的循环递减有效,但不确定为什么

  • 本文关键字:不确定 有效 循环 c cs50
  • 更新时间 :
  • 英文 :


我试图搜索已经提出的类似问题,但找不到。代码在帖子末尾。谢谢你抽出时间。


问题:虽然我的代码可以正确地执行赋值,但我不确定为什么我的for循环只能按规定工作。

为了澄清我的代码应该做什么:取用户输入的数字,构建两个半金字塔:一个递减,一个递增

下面是一个图像示例:金字塔示例


问题:在循环的当前递减中,我有:for (int s = u - y; s > 1; s--)

循环的有效。但当我尝试for (int s = u - 1; s > 1; s--)for (int s = u; s > 1; s--)时,它不会递减。

为什么循环的仅在I使用y变量减法时递减?

这是我的代码:

#include <stdio.h>
#include <cs50.h>
int main(void)
{
// Get a number value from User (u) that is between 1 and 8.
int u;
do
{
u = get_int("Type a number: n");
}
while (u < 1 || u > 8);

// Print a new line each loop, until reaching User number (u)
for (int y = 0; y < u; y++)
{
// Print a "." by (u - 1) number of times. Subtract another "." each loop
for (int s = u - y; s > 1; s--)
{
printf(".");
}
// Print a "#" by (y) number of times. Add another "#" each loop
for (int width = 0; width <= y; width++)
{
printf("#");
}
printf("n");
}
}
ChoKaPeek在评论中回答了这个问题。这里有另一种方法,使用C的格式化输出指定可变字段宽度的能力:
char* dots = "........";
char* octos = "########";
for (int nOctos=0; nOctos <= u; nOctos++) {
printf("%.*s%.*sn", u-nOctos, dots, nOctos, octos);
}

分解:

CCD_ 4表示";我正在传递参数列表中的CCD_ 5";

CCD_ 6表示";使用字段宽度";

CCD_ 7表示";字段宽度在CCD_ 8〃之前的参数中;

相关内容

最新更新