c - 如何使这段代码形成的金字塔(CS50马里奥程序)右对齐?

标签 c stdio cs50

请帮助我使用右对齐的哈希值和空格正确打印高度为“n”的金字塔。我已在下面发布了代码本身。该程序正确地要求用户输入,但不会构建右对齐的金字塔。如果有人能解决这个问题,请帮忙。

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

int main(void)
{
    int i=0;
    int n=0;

    do
    {
        printf("Height:");
        n=GetInt();
    } while (n<0 || n>23);

    for (i=0; i<n; i++)
    {
        printf(" ");
        for (int x=0; x<i+2; x++)
        {
            printf("#");
        }
        printf("\n");
    }

    return 0;
}

最佳答案

这是正确的解决方案之一!

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

void buildPyramid(int height);

int main(void)
{
    // Initialize the variable height
    int height;

    // Run the loop to get a value of height between 1 and 8, inclusive, from the user
    do
    {
        height = get_int("Height: ");
    }
    while (height < 1 || height > 8);

    // Call the function and pass height to it as a parameter
    buildPyramid(height);
}

// Declare the function buildPyramid
void buildPyramid(int height)
{
    // Loop to add a new line
    for (int i = 0; i < height; i++)
    {
        // Loop to add spaces
        for (int k = height - i; k > 1; k--)
        {
            printf(" ");
        }
        // Loop to add hashes
        for (int j = 0; j <= i; j++)
        {
            printf("#");
        }
        printf("\n");
    }
} 

关于c - 如何使这段代码形成的金字塔(CS50马里奥程序)右对齐?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32303244/

相关文章:

c - 程序在 printArray 处崩溃

c - 我的 cs50 vigenere 代码有什么问题?我很接近输出

c - 为什么这两个字符串在c中不相等

c - Speller - 卸载特里树 - 功能无法正常工作

c - 如何使用 Visual Studio 调试 SQLite 源代码

c - 在 openGL 中寻找聚光灯 vector

c - 从cygwin移动到VisualStudio2013,报错LNK2019,snprintf(),c

c - 打开 .c 文件时自动包含头文件

C:将两个文件指针同步到同一个文件

c - 如何使用涉及多次读写的管道在子进程和父进程之间实现双向通信