C中的星号金字塔 [英] Asterisk Pyramid in C

查看:149
本文介绍了C中的星号金字塔的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

练习:制作一个程序,该程序读取自然数 n 并绘制一个星号金字塔. n = 5的模型:

Exercise: make a program that reads a natural number n and draws a pyramid of asterisks. Model for n = 5:

    *
   ***
  *****
 *******
*********

代码:

int main ()
{
    int n, i, j=1, aux1, aux2;
    int spaces=1;
    scanf ("%d", &n);

    for (i=0; i<n; i++)
    {
        spaces += 1;
    }
    printf ("\n");
    for (i=0; i<n; i++)
    {
        aux1 = j;
        aux2 = spaces;

        while (aux2 >= 1)
        {
            printf (" ");
            aux2--;
        }

        while (aux1 >= 1)
        {
            printf ("*");
            aux1--;
        }

        j += 2;
        spaces--;

        printf ("\n");
    }

    return 0;
}

我的代码正在接受在线评委的演示错误",因为每行的最后星号后面都有一个空格. 有关如何修复它的任何提示?

My code is receiving "Presentation Error" from online judge because the last asterisks of every line have a space after. Any tips on how to fix it?

推荐答案

您的代码在每行的开头而不是结尾都有空格.

Your code has spaces at the start of each line, not the end.

这是我想解决该问题的最简单方法:

Here is the simplest way I can think of to go about solving that problem:

#include <stdio.h>
#include <stdlib.h>


int main(void)
{
    int i, j, height;

    scanf("%d", &height);

    for (i = 0; i < height; i++) {
        for (j = 0; j < height - i - 1; j++)
            putchar(' ');

        for (; j < height + i; j++)
            putchar('*');

        putchar('\n');
    }

    return EXIT_SUCCESS;
}

这篇关于C中的星号金字塔的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

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