想要在C中的下一个循环中使用变量

时间:2018-11-10 23:07:22

标签: c cs50

我是初学者,正在尝试做CS50马里奥金字塔的左半部分 像这样(成像s只是空白)

ssss#
sss##
ss###
s####

经过大量思考,我认为此公式应该有效

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

int main(void)

{
 int n = get_int("Height: ");
 for (int i = 0; i < n; i++)
 {

  // s stands for spaces
    for (int s = 0; s < n - 1 - i; s++)


       printf(" ");

  // h stands for hashes
    for (int h = 0; h < n - s; h++)
       printf("#");
       printf("\n");

 }

printf("\n");
}
如您所见

我想使用变化的变量s的值并在下一个变量h中使用它 我知道它的价值只有() 当我尝试添加{}时

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

int main(void)

{
 int n = get_int("Height: ");
 for (int i = 0; i < n; i++)
 {

  // s stands for spaces
    for (int s = 0; s < n - 1 - i; s++)

{
       printf(" ");


  // h stands for hashes
    for (int h = 0; h < n - s; h++)
       printf("#");
       printf("\n");
       }

 }

printf("\n");
}

它避免了printf(“”)行,并先打印#导致出现这样的事情

 
####
###
##
####
###
####

所以我怎样才能通过(INput-1-行)的数量先将其打印到打印空间,然后再打印哈希(输入变量哈希) 这样在四行金字塔的第二行中我得到(4-1-1 = 2个空格)然后散列(input-个空格)(4-2 = 2)  ss ## 第三行(4-1-2 = 1)(4-3 = 1)  s ### 等等。

3 个答案:

答案 0 :(得分:1)

您可以在循环外部声明索引变量(s),以便在循环结束后它会保留其值,以便您执行所需的操作。

答案 1 :(得分:1)

for循环中声明的变量在此循环范围之外不可访问。如果要在循环外访问变量,请在循环外定义/声明它;例如:

// s stands for spaces
int s;
for (s=0; s < n - 1 - i; s++) {
   printf(" ");
}

// h stands for hashes
for (int h = 0; h < n - s; h++) { 
   ...

答案 2 :(得分:1)

如果我复制问题中的代码并设置其格式,则它看起来像这样:

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

int main(void)
{
    int n = get_int("Height: ");
    for (int i = 0; i < n; i++)
    {
        // s stands for spaces
        for (int s = 0; s < n - 1 - i; s++)
        {
            printf(" ");
            // h stands for hashes
            for (int h = 0; h < n - s; h++)
                printf("#");
            printf("\n");
        }
    }

    printf("\n");
}

循环结构不是预期的; h循环可以访问s,但是不能访问。 i循环从零开始计数(但不包括)输入的数字。您要打印i + 1哈希,因此实际上不需要在循环后访问s

正如我在评论中指出的那样,在s循环的结尾,s的值为n - 1 - i;您可以在下一个循环的极限表达式中使用它:for (int h = 0; h < n - (n - 1 - i); h++),但随后可以将其简化为for (int h = 0; h < i + 1; h++),因此您确实不需要在之后访问s它的循环结束。

这个混杂的循环代码的高度7的输出如下:

Height: 7
 #######
 ######
 #####
 ####
 ###
 ##
 #######
 ######
 #####
 ####
 ###
 #######
 ######
 #####
 ####
 #######
 ######
 #####
 #######
 ######
 #######

如果您修改了代码以使h循环不在s循环之内,并按照所讨论的那样对h循环进行了限制,那么您将得到如下代码: / p>

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

int main(void)
{
    int n = get_int("Height: ");
    for (int i = 0; i < n; i++)
    {
        // s stands for spaces
        for (int s = 0; s < n - 1 - i; s++)
            printf(" ");
        // h stands for hashes
        for (int h = 0; h < i + 1; h++)
            printf("#");
        printf("\n");
    }

    printf("\n");
}

高度7的相应输出为:

Height: 7
      #
     ##
    ###
   ####
  #####
 ######
#######

这看起来像是想要的。