如何进行这项练习? (C)

时间:2011-06-10 14:49:31

标签: c

“让程序请求用户输入大写字母。使用嵌套循环生成这样的金字塔图案:

    A

   ABA

  ABCBA

 ABCDCBA

ABCDEDCBA

模式应扩展为输入的字符。例如,前面的模式将由E的输入值产生。“

到目前为止,我已经这样做了好几个小时了,我正在通过字母表向前搜索字母时,正确地为字母格式化“金字塔”:

#include <stdio.h>
int main(void)
{
    char ch = 0;
    char ch2 = 0;
    int rows = 0;
    printf("Enter a character: ");
    scanf("%c", &ch);
    rows = ch - 64;
    while(rows > 0)
    {
        int spaces;
        for(spaces = rows-1; spaces > 0; spaces--)
        {
            printf(" ");
        }
        ch2 = 65;
        while(ch2 < (ch-(rows-2)))
        {
            printf("%c", ch2);
            ch2++;
        }

        printf("\n");
        rows--;
    }
}

然而,我觉得好像我已经碰到了一堵砖墙,试图让它适当地向后迭代。我知道应该只是一些基本的循环,但我很好,真的卡住了。我相信这很容易......我想我已经看了太久了。想法?

4 个答案:

答案 0 :(得分:1)

你是如此亲密,你只需要喘口气,你就会看到它。

当你打印出你的角色时,必须在这部分之后完成

    while(ch2 < (ch-(rows-2)))
    {
        printf("%c", ch2);
        ch2++;
    }

或者它不会落在字符串的末尾。你需要的是另一个循环,它从最后一个字符下面的字符开始。它应该打印一个角色并减少该角色,直到它打印出“A&#39; A&#39;字符。

由于这是作业,我会给你一个机会来写这个循环,然后再告诉你确切的细节。

答案 1 :(得分:1)

有些方法可能会重写这段代码以使其更清晰,但基于你所拥有的东西,这样的东西可能会在你当前的循环之后正常工作。

while (ch2 > 'A')
{
    ch2--;
    printf("%c", ch2);
}

我建议尝试重构一下代码以使其更清晰。正如我在评论中建议的那样,首先使用字符文字而不是原始整数。

答案 2 :(得分:0)

你可以向下迭代:

while(ch2 >= 'A')
{
    printf("%c", ch2);         
    ch2--;         
} 

答案 3 :(得分:0)

试试这个:

#include <stdio.h>

int main (int argc, const char * argv[])
{
    char ch;

    printf("Enter a character: ");
    scanf("%c", &ch);
    if(ch<'A' || ch>'Z'){
        printf("Character must be between 'A' and 'Z'\n");
        return 1;
    }

    for(int rows = ch - 'A'; rows >= 0; rows--)
    {
        char ch2;
        for(int spaces = rows; spaces > 0; spaces--)
            printf(" ");

        for(ch2='A'; ch2 < (ch-(rows-1)); ch2++) 
            printf("%c", ch2);

        for(ch2=ch2-2;ch2>='A';ch2--)
            printf("%c", ch2);

        printf("\n");
    }
    return 0;
}