【问题标题】:C - nested for loop paternC - 嵌套 for 循环模式
【发布时间】:2017-10-05 12:55:48
【问题描述】:

如何获得像翻转的弗洛伊德三角形一样的输出?最好的解决方法是什么?

例子:

5555
_555
__55
___5

注意:_ 是空格

已经尝试了很多代码,但我仍然无法获得这样的输出。

我的一个代码:

#include<stdio.h>

int main () {
    int a,b,c,n;
    scanf("%d",&n);
    for(a=1;a<=n;a++) {
        for(b=n;b>=a;b--) {
            printf(" ");
        }
        for(c=1;c<=a;c++) {
            printf("*");
        }
        printf("\n");
    }
}

【问题讨论】:

  • 显示你的代码..,
  • 显示已经尝试了很多代码
  • @BLUEPIXY 他试了这么多代码,所有的代码都不能放在问题里。没有足够的空间。
  • @Sourav Ghosh #include int main () { int a,b,c,n; scanf("%d",&n); for(a=1;a=a;b--) { printf(" "); } for(c=1;c
  • @soloemollyn 好吧,欢迎!我个人更喜欢在交流时使用更正式的地址。

标签: c for-loop


【解决方案1】:

这不是最好的方法...但是代码与您发布的代码相似。

int main()
{
    int a, b, c, n;
    scanf("%d", &n);
    for (a = n; a > 0; a--)
    {
        for (b = n; b >= a; b--)
        {
            printf(" ");
        }
        for (c = 1; c <= a; c++)
        {
            printf("*");
        }
        printf("\n");
    }
}

在原始帖子中,您的第一个 for 循环是

for(a=1;a<=n;a++)

这意味着第二个 for 循环将打印 n*space,第三个 for 循环将打印 1 颗星。 通过将第一个 for 循环更改为

for (a = n; a > 0; a--)

一切都被颠倒了,所以第一个循环将不打印空格,最后一个循环 n*stars。

【讨论】:

  • 所以它会窃取我的信用卡号码?不,谢谢。 :)
【解决方案2】:

开玩笑;)

#include <stdio.h>

int main( void )
{
    int n = 5555;

    while (n)
    {
        printf("%5d\n", n);
        n /= 10;
    }

    return 0;
}

程序输出和要求的一样。:)

 5555
  555
   55
    5

如果使用循环,那么程序可能看起来像

#include <stdio.h>

int main( void )
{
    const char c = '5';

    while (1)
    {
        printf("Enter a non-negative number (0 - exit): ");

        unsigned int n;

        if (scanf("%u", &n) != 1 || n == 0) break;

        putchar('\n');

        for (unsigned int i = 0; i < n; i++)
        {
            unsigned int j = i + 1;
            printf("%*c", (int)j, c);
            while (j++ < n) putchar(c);
            putchar('\n');
        }

        putchar('\n');
    }

    return 0;
}

它的输出可能看起来像

Enter a non-negative number (0 - exit): 10

5555555555
 555555555
  55555555
   5555555
    555555
     55555
      5555
       555
        55
         5

Enter a non-negative number (0 - exit): 0

内部的while循环可以代替for循环

for ( ; j < n; j++ )

【讨论】:

  • 如果我的讲座没有告诉我在嵌套 for 循环中执行它,我会这样写下来的事情 XD
猜你喜欢
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2021-03-20
  • 2017-07-29
  • 2022-01-26
  • 2016-04-22
相关资源
最近更新 更多