请问这个℃,循环打印文本的艺术金字塔? [英] How does this C for-loop print text-art pyramids?

查看:87
本文介绍了请问这个℃,循环打印文本的艺术金字塔?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

这是我第一次张贴在这里,希望我这样做是正确的。

This is my first time posting in here, hopefully I am doing it right.

基本上我需要帮助,试图找出一些code,我写了使用类C.该计划的目的是要求用户在0到23之间的数字。然后,根据用户的数量输入,一个半锥体将被打印(如在老同学马里奥游戏的那些)。我在编程初学者,得到的答案侥我的code,但现在我真的不能告诉我的for循环如何提供金字塔的身影。

Basically I need help trying to figure out some code that I wrote for class using C. The purpose of the program is to ask the user for a number between 0 and 23. Then, based on the number the user inputted, a half pyramid will be printed (like the ones in the old school Mario games). I am a beginner at programming and got the answer to my code by mere luck, but now I can't really tell how my for-loops provide the pyramid figure.

#include <stdio.h>

int main ( void )
{
    int user_i;
    printf ( "Hello there and welcome to the pyramid creator program\n" );
    printf ( "Please enter a non negative INTEGER from 0 to 23\n" );
    scanf ( "%d", &user_i );

    while ( user_i < 0 || user_i > 23 )
    {
        scanf ( "%d", &user_i );
    }

    for ( int tall = 0; tall < user_i; tall++ )
    {
        // this are the two for loops that happened by pure magic, I am still
        // trying to figure out why are they working they way they are
        for ( int space = 0; space <= user_i - tall; space++ )
        {
            printf ( " " );
        }
        for ( int hash = 0; hash <= tall; hash++ )
        {
            printf ( "#" );
        }
        // We need to specify the printf("\n"); statement here
        printf ( "\n" );
    }

    return 0;
}

作为新的节目我也跟着我所知道的伪code少了什么,我似乎无法理解为什么for循环部分正在工作事情是这样的。据我所知,while循环完美(虽然改正和最佳实践的欢迎),但for循环逻辑继续逃避我,我想继续之前充分理解这一点。任何帮助将大大AP preciated。

Being new to programming I followed what little I know about pseudocode, I just can't seem to understand why the for-loop section is working the way it is. I understand the while loop perfectly (although corrections and best practices are welcomed), but the for-loop logic continues to elude me and I would like to fully understand this before moving on. Any help will be greatly appreciated.

推荐答案

我将解释我是如何来理解这个code的地步,我会用它自己舒服的过程。我将pretend,我没有看到你的描述,让我从头开始。这个过程被分为因为我去,我会分几个阶段。我的目标是给一些通用的技术,这将使得程序更易于阅读。

I will explain the process of how I would come to understand this code to the point where I would be comfortable using it myself. I will pretend that I did not read you description, so I am starting from scratch. The process is divided into stages which I will number as I go. My goal will be to give some general techniques which will make programs easier to read.

第一步将是笼统什么程序没有做详细陷入困境理解。让我们开始阅读的主要功能体。

The first step will be to understand in general terms what the program does without getting bogged down in details. Let's start reading the body of the main function.

int main(void) {
    int user_i;
    printf("Hello there and welcome to the pyramid creator program\n");
    printf("Please enter a non negative INTEGER from 0 to 23\n");
    scanf("%d", &user_i);

到目前为止,我们在整数宣布,并告诉用户输入一个号码,然后使用 scanf函数函数来设置整数等于用户输入的内容。不幸的是它是从提示或code什么整数的目的不清楚。让我们继续阅读。

So far, we have declared in integer, and told the user to enter a number, and then used the scanf function to set the integer equal to what the user entered. Unfortunately it is unclear from the prompt or the code what the purpose of the integer is. Let's keep reading.

    while (user_i < 0 || user_i > 23) {
        scanf("%d", &user_i);
    }

在这里,我们可能要求用户输入更多的整数。通过提示来看,它似乎是一个不错的猜测,这句话的目的是为了确保我们的整数是在合适的范围,这是很容易通过检查code检查。让我们来看看下一行

Here we possibly ask the user to enter additional integers. Judging by the prompt, it seems like a good guess that the purpose of this statement is to make sure that our integer is in the appropriate range and this is easy to check by examining the code. Let's look at the next line

     for (int tall = 0; tall < user_i; tall++) {

这是对环外。我们神秘的整数 user_i 再次出现,我们有另一个整数高大这之间的 0会 user_i 。让我们来看看一些code。

This is the outer for loop. Our enigmatic integer user_i appears again, and we have another integer tall which is going between 0 and user_i. Let's look at some more code.

        for (int space = 0; space <= user_i - tall; space++) {
            printf(" ");
        }

这是第一个内循环。我们不要在正在发生的事情与此新的整数的细节陷入下跌空格为什么我们有 user_i - 高大出现,但我们只是注意,福尔循环体只是打印出空间。所以这个循环只是有打印一堆空间的效果。让我们看看接下来的内循环。

This is the first inner for loop. Let's not get bogged down in the details of what is going on with this new integer space or why we have user_i - tall appearing, but let's just note that the body of the foor loop just prints a space. So this for loop just has the effect of printing a bunch of spaces. Let's look at the next inner for loop.

        for (int hash = 0; hash <= tall; hash++) {
            printf("#");
        }

这一个看起来相似。它只是打印一串散列。接下来我们

This one looks similar. It just prints a bunch of hashes. Next we have

        printf("\n");

这显示新的一行。接下来是

This prints a new line. Next is

    }

    return 0;
}

这意味着,对于环的外端,和外循环结束后,程序结束。

This means that the outer for loop ends, and after the outer for loop ends, the program ends.

注意,我们已经发现了两个主要部分为code。第一件是,可以得到一个值,以 user_i ,和第二片,外循环,必须在这里该值用于绘制金字塔。接下来让我们尝试找出 user_i 表示。

Notice we have found two major pieces to the code. The first piece is where a value to user_i is obtained, and the second piece, the outer for loop, must be where this value is used to draw the pyramid. Next let's try to figure out what user_i means.

现在因为新行打印的外部循环的每次迭代,和神秘的 user_i 控制外循环的多次迭代怎么有,因此多少新行打印,它似乎 user_i 控制所创建的金字塔的高度。为了得到确切的关系,让我们假设 user_i 的值为 3 ,那么高大将采取上的值0,1和2,和因此该循环将执行三次,金字塔的高度将是三种。还要注意的是,如果 user_i 将一个增加,则循环将执行一次,并金字塔将由一个更高。这意味着 user_i 必须是金字塔的高度。让我们重命名变量 pyramidHeight 我们忘记了。我们的主要功能,现在看起来是这样的:

Now since a new line is printed for every iteration of the outer loop, and the enigmatic user_i controls how many iterations of the outer loop there are, and therefore how many new lines are printed, it would seem that user_i controls the height of the pyramid that is created. To get the exact relationship, lets assume that user_i had the value 3, then tall would take on the values 0,1, and 2, and so the loop would execute three times and the height of the pyramid would be three. Notice also that if user_i would increase by one, then the loop would execute once more and the pyramid would be higher by one. This means that user_i must be the height of the pyramid. Let's rename the variable to pyramidHeight before we forget. Our main function now looks like this:

int main(void) {
    int pyramidHeight;
    printf("Hello there and welcome to the pyramid creator program\n");
    printf("Please enter a non negative INTEGER from 0 to 23\n");
    scanf("%d", &pyramidHeight);
    while (pyramidHeight < 0 || pyramidHeight > 23) {
        scanf("%d", &pyramidHeight);
    }

    for (int tall = 0; tall < pyramidHeight; tall++) {
        for (int space = 0; space <= pyramidHeight - tall; space++) {
            printf(" ");
        }
        for (int hash = 0; hash <= tall; hash++) {
            printf("#");
        }
        printf("\n");
    }

    return 0;
}

第3步:制作,获取金字塔高度的函数

既然我们理解了code的第一部分,我们可以把它移动到一个功能,而不是去想它了。这将使code更易于阅读。由于code,这部分是负责获得有效的高度,让我们致电funcion getValidHeight 。这样做了以后,发现金字塔的高度将不会在办法改变,所以我们可以声明为 const int的。我们code现在看起来是这样的:

Stage 3: Make a function that gets the pyramid height

Since we understand the first part of the code, we can move it into a function and not think about it anymore. This will make the code easier to look at. Since this part of the code is responsible for obtaining a valid height, let's call the funcion getValidHeight. After doing this, notice the pyramid height will not change in the main method, so we can declare it as a const int. Our code now looks like this:

#include <stdio.h>

const int getValidHeight() {
    int pyramidHeight;
    printf("Hello there and welcome to the pyramid creator program\n");
    printf("Please enter a non negative INTEGER from 0 to 23\n");
    scanf("%d", &pyramidHeight);
    while (pyramidHeight < 0 || pyramidHeight > 23) {
        scanf("%d", &pyramidHeight);
    }
    return pyramidHeight;
}

int main(void) {
    const int pyramidHeight = getValidHeight();
    for (int tall = 0; tall < pyramidHeight; tall++) {
        for (int space = 0; space <= pyramidHeight - tall; space++) {
            printf(" ");
        }
        for (int hash = 0; hash <= tall; hash++) {
            printf("#");
        }
        printf("\n");
    }

    return 0;
}

第四步:了解内部for循环

我们知道内部for循环重复打印字符,但究竟有多少次?让我们考虑的第一个内循环。有多少空间都印?你可能会认为,通过与外循环的比喻有 pyramidHeight - 高大的空间,但在这里,我们有空间&LT; = pyramidHeight - 高大,其中真正的类似情况会空间&LT; pyramidHeight - 高大。既然我们有&LT; = ,而不是&LT; ,我们得到一个额外的迭代,其中空间等于 pyramidHeight - 高大。因此,我们看到实际上 pyramidHeight - 高大+ 1 空格打印。同样高大+ 1 哈希打印。

Stage 4: understand the inner for loops.

We know the inner for loops print a character repeatedly, but how many times? Let's consider the first inner for loop. How many spaces are printed? You might think that by analogy with the outer for loop there are pyramidHeight - tall spaces, but here we have space <= pyramidHeight - tall where the truly analogous situation would be space < pyramidHeight - tall. Since we have <= instead of <, we get an extra iteration where space equals pyramidHeight - tall. Thus we see that in fact pyramidHeight - tall + 1 spaces are printed. Similarly tall + 1 hashes are printed.

由于打印字符多次很容易理解,我们可以将这个code到自己的职能。让我们来看看我们的code貌似现在。

Since printing a character multiple times is easy to understand, we can move this code into their own functions. Let's see what our code looks like now.

#include <stdio.h>

const int getValidHeight() {
    int pyramidHeight;
    printf("Hello there and welcome to the pyramid creator program\n");
    printf("Please enter a non negative INTEGER from 0 to 23\n");
    scanf("%d", &pyramidHeight);
    while (pyramidHeight < 0 || pyramidHeight > 23) {
        scanf("%d", &pyramidHeight);
    }
    return pyramidHeight;
}

void printSpaces(const int numSpaces) {
    for (int i = 0; i < numSpaces; i++) {
        printf(" ");
    }
}

void printHashes(const int numHashes) {
    for (int i = 0; i < numHashes; i++) {
        printf("#");
    }
}

int main(void) {
    const int pyramidHeight = getValidHeight();
    for (int tall = 0; tall < pyramidHeight; tall++) {
        printSpaces(pyramidHeight - tall + 1);
        printHashes(tall + 1);
        printf("\n");
    }

    return 0;
}

现在,当我看功能,我不必担心如何 printSpaces 实际打印的空间。如果它使用了环或,而循环我已经忘记了。这将释放我的脑涨去想其他的事情。

Now when I look at the main function, I don't have to worry about the details of how printSpaces actually prints the spaces. I have already forgotten if it uses a for loop or a while loop. This frees my brain up to think about other things.

我们的的功能是现在很容易阅读。我们准备开始思考其实际作用。 for循环的每次迭代打印一定数量的空格后面一定数量的哈希值后跟一个新行。由于空间首先打印,他们都将在左边,这就是我们想要得到它给我们的画面。

Our main function is now easy to read. We are ready to start thinking about what it actually does. Each iteration of the for loop prints a certain number of spaces followed by a certain number of hashes followed by a new line. Since the spaces are printed first, they will all be on the left, which is what we want to get the picture it gives us.

由于新的生产线都印岁以下的线路终端上,化零为的值高大相当于金字塔的顶端一行。

Since new lines are printed below old lines on the terminal, a value of zero for tall corresponds to the top row of the pyramid.

由于考虑到这些事情,让我们引入两个新的变量, numSpaces numHashes 为空格的数量和哈希值,以迭代打印。因为这些变量的值不以单次迭代变化,我们可以使他们的常数。也让我们改变名称高大(这是一个形容词,因此一个不好的名字为整数) distanceFromTop 。我们新的主要方法看起来像这样

With these things in mind, let's introduce two new variables, numSpaces and numHashes for the number of spaces and hashes to be printed in an iteration. Since the value of these variables does not change in a single iteration, we can make them constants. Also let's change the name of tall (which is an adjective and hence a bad name for an integer) to distanceFromTop. Our new main method looks like this

int main(void) {
    const int pyramidHeight = getValidHeight();

    for (int distanceFromTop = 0; distanceFromTop < pyramidHeight; distanceFromTop++) {
        const int numSpaces = pyramidHeight - distanceFromTop + 1;
        const int numHashes = distanceFromTop + 1;
        printSpaces(numSpaces);
        printHashes(numHashes);
        printf("\n");
    }

    return 0;
}

阶段7:为什么 numSpaces numHashes 它们是什么

所有内容都撞在了一起。留下来找出的唯一事情就是给公式 numSpaces numHashes

让我们先从 numHashes ,因为它更容易理解。我们希望 numHashes 来为一个当从顶部的距离是零,我们希望 numHashes 一个每当增加从顶部的距离呢,所以正确的公式是 numHashes = distanceFromTop + 1

Let's start with numHashes because it is easier to understand. We want numHashes to be one when the distance from the top is zero, and we want numHashes to increase by one whenever the distance from the top does, so the correct formula is numHashes = distanceFromTop + 1.

现在的 numSpaces 。我们知道,每一次从顶部的距离增加,空间变成散列,所以有一个更小的空间。因此,对于 numSpaces 除权pression应该在它有一个 -distanceFromTop 。但究竟有多少空间应该排在前列有哪些?由于顶行已经有了一个哈希,有 pyramidHeight - 1 来进行需要的哈希值,所以必须至少 pyramidHeight - 1 的空间,使他们可以变成哈希值。在code,我们选择了 pyramidHeight +排在前列,这比 pyramidHeight两个1 空间 - 1 ,所以有权两个空格整个画面移动的效果。

Now for numSpaces. We know that every time the distance from the top increases, a space turns into a hash, and so there is one less space. Thus the expression for numSpaces should have a -distanceFromTop in it. But how many spaces should the top row have? Since the top row already has a hash, there are pyramidHeight - 1 hashes that need to be made, so there must be at least pyramidHeight - 1 spaces so they can be turned into hashes. In the code we have chosen pyramidHeight + 1 spaces in the top row, which is two more than pyramidHeight - 1, and so has the effect of moving the whole picture right by two spaces.

您只要求两内环是如何工作的,但我给了一个很长的答案。这是因为我认为,真正的问题不在于你不知道如何为循环工作足够好,而是你的code,很难读懂,所以它很难说什么事情在做。所以,我给你,我怎么会写程序,希望你会觉得它更容易阅读,因此,您将能够看到更清楚下去,并希望所以你可以学写更清楚code你自己。

You were only asking how the two inner loops worked, but I gave a very long answer. This is because I thought the real problem was not that you didn't understand how for loops work sufficiently well, but rather that your code was difficult to read and so it was hard to tell what anything was doing. So I showed you how I would have written the program, hoping that you would think it is easier to read, so you would be able to see what is going on more clearly, and hopefully so you could learn to write clearer code yourself.

我怎么改变code?我改变了变量所以很清楚每个变量的作用是的姓名;我引入了新的变量,并试图给他们好名字为好;我有些感动,涉及的输入和输出,并打印字符一定数量的次进入自己的方法的逻辑下级code的。这最后的变化极大地降低了函数的行数
,摆脱了嵌套在函数循环运行,并取得了该方案容易看到的主要逻辑。

How did I change the code? I changed the names of the variables so it was clear what the role of each variable was; I introduced new variables and tried to give them good names as well; and I moved some of the lower level code involving input and output and the logic of printing characters a certain number of times into their own methods. This last change greatly decreased the number of lines in the main function , got rid of the nesting of for loops in the main function, and made the key logic of the program easy to see.

这篇关于请问这个℃,循环打印文本的艺术金字塔?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆