-1

在正确“链接”了所有头文件后,我终于达到了能够正确编译代码的程度。当我执行 mariov1.c(代码如下所示)时,我使用了 20 的测试输入,结果是打印输出 3 个哈希标记,然后显示我的 cmd 行,如下所示

###[xvp@localhost ~]$

现在它应该有 21 个空格和 2 个哈希标记的输出,每行添加一个哈希标记并减去一个空格,直到哈希标记的数量 = usrHeight (本质上它实际上并没有设置为由哈希的数量决定,但它仍然有效方式)。应该看起来像这样。

How High?
10
constructing...
         ##
        ###
       ####
      #####
     ######
    #######
   ########
  #########
 ##########
###########

这将使其保持正确对齐。

mariov1.c 源码

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

int main(void)
{
    int usrHeight = 0;
    int levelCounter = 0;
    int paddIt = usrHeight - 1;
    int hashCounter = 2;


    do 
    {
        printf("How high?\n");
        int usrHeight = GetInt();
    }
    while ( usrHeight > 23 || usrHeight < 0);
    if ( usrHeight >= 0 && usrHeight <= 23);
    {
        printf("constructing...\n");

    }
    for (levelCounter = 0; levelCounter <= usrHeight; levelCounter++)
    {
            printf("%.*s\n", paddIt, "");
            for (int i = 0; i <= hashCounter; i++)
                putchar('#'); 
            paddIt = paddIt - 1;
            hashCounter = hashCounter + 1;
    }

}

在这个错误之后我进行了第二次尝试,使用了另一个 do while 循环,中间有一个 for 循环(很确定我做错了),但它只是不断地用哈希填充终端,所以我不知道该去哪里观点。

这是 mariov2.c 源

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

int main(void)
{
    int usrHeight = 0;
    int levelCounter = 0;
    int paddIt = usrHeight - 1;
    int hashCounter = 2;


    do 
    {
        printf("How high?\n");
        int usrHeight = GetInt();
    }
    while ( usrHeight > 23 || usrHeight < 0);
    if ( usrHeight >= 0 && usrHeight <= 23);
    {
        printf("constructing...\n");

    }
    //doing a test to see if this do while loop will handle this appropriatelly
    do
    {
        printf("%.*s\n", paddIt, "");
            for (int i = 0; i <= hashCounter; i++)
        {
            putchar('#');
            paddIt = paddIt - 1;
            hashCounter = hashCounter + 1;
            levelCounter = levelCounter + 1;
        }   
    }
    while ( levelCounter <= usrHeight );
    //commented area part of original code
    //for (levelCounter = 0; levelCounter <= usrHeight; levelCounter++)
    //{
        //  printf("%.*s", paddIt, "");
        //  for (int i = 0; i <= hashCounter; i++)
        //      putchar('#'); 
        //  paddIt = paddIt - 1;
        //  hashCounter = hashCounter + 1;
    //}

}
4

1 回答 1

2

首先要注意的是,usrHeight您在循环中使用的总是0因为在段中

do 
{
    printf("How high?\n");
    int usrHeight = GetInt();
}
while ( usrHeight > 23 || usrHeight < 0);

usrHeight是 this while 范围的本地。一旦控件超出此范围并且您使用usrHeight它实际上是您在函数 main 范围内定义的变量。int从中删除int usrHeight = GetInt();

paddIt此外,您在实际使用值初始化变量之前已经计算了变量GetInt ()

于 2014-02-07T04:29:19.163 回答