ç打印空间金字塔 [英] C print space pyramid

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

问题描述

我要打印这样的:

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

而是我得到这样的:

but instead I get this:

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

下面是我的code:

#include<stdio.h>
int main()
{
    int rows,i,j,space;

    rows = 5;
    //printf("Enter number of rows: ");
    //scanf("%d",&rows);
    for(i=rows;i>=1;--i)
    {
        for(space=0;space<rows-i;++space)
           printf("*");
        for(j=i;j<=2*i-1;++j)
          printf(" ");
        for(j=0;j<i-1;++j)
            printf(" ");
        printf("\n");
    }
    return 0;
}

有什么不对呢?谁能帮我?我已经尝试了许多选择,但他们都不打印我想要的。谢谢

What is wrong with this? Can anyone help me? I have tried many options but none of them prints what I want. Thanks

推荐答案

有几件事情错在这里。

首先,让我们来解决你的第三个循环。该方案应重新打印星星,空格,然后恒星,使第三循环不应该是打印的空间。同时,我们也印刷在空间两侧的恒星相同数量,所以第三个循环将实际上只是在完全相同code 作为你的第一个循环!

First let's address your third loop. The program should print stars, spaces, and then stars again, so that third loop shouldn't be printing spaces. Also, we're printing the same amount of stars on either side of the spaces, so the third loop will actually just be the same exact code as your first loop!

其次,在这里的第二环路的标题

Secondly, here in the header of the second loop:

for(j=i;j<=2*i-1;++j)

您错过parenthises。通过操作顺序,这将作为评估(2 * I)-1 ,这是不是你想要的。

You're missing parenthises. By the order of operations, this will evaluate as (2*i)-1, which isn't what you want.

这里还有一个棘手的警告!你将你的例子输出的第一行中看到有一个 奇数的明星,而所有其他行有偶数个!仅在第一线,我们需要确切地少了一个明星打印!这意味着我们需要这样code在我们的明星之一,循环忽略第一行的第一球星:

There is also a tricky caveat here! You'll notice in the first row of your example output there's an odd number of stars, while every other line has an even number! In the first line only, we need to print exactly one less star! Which means we'll need this code in one of our star loops to ignore the first star of the first row:

if(i !=0 || space != 0) printf("*");

最后,我翻转你的外循环迭代的其他方式,因为它看起来像,这是你想要什么,它有助于解决一些其他问题:

Lastly, I've flipped your outer loop to iterate the other way, as it looked like that was what you wanted and it helped to solve some other problems:

for(i=0;i<rows;++i)
{
    for(space=0;space<rows-i;++space)
       if(i!=0 || space != 0) printf("*");
    for(j=0;j<2*(i-1)+1;++j)
      printf(" ");
    for(space=0;space<rows-i;++space)
       printf("*");
    printf("\n");
}

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

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