请帮助我使用右对齐的哈希值和空格正确打印高度为“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/