蛇形数字三角形怎么做?c++

蛇形数字三角形怎么做?c++

问题描述:

题目描述

输入一个正整数N,输出N行的蛇形数字三角形(具体看样例)。

输入

一行一个正整数,3 ≤ N ≤ 30.

输出

N行,第一行N个数,第二行N - 1个数,……第N行一个数。每个数占5列。

样例输入

9

样例输出

    1    2    4    7   11   16   22   29   37
    3    5    8   12   17   23   30   38
    6    9   13   18   24   31   39
   10   14   19   25   32   40
   15   20   26   33   41
   21   27   34   42
   28   35   43
   36   44
   45

#include <stdio.h>
#include <stdbool.h>
int cnt = 0;
int a[26][50];
int n;

void f(int top, int bottom)
{
	int i, j;
	if(top<(n+1)/4)
		return;
	for(j=n-bottom+1; j<bottom; ++j)
		a[top][j] = ++cnt;
	for(i=top; i>(1+n)/2-top+1; --i, --j)
		a[i][j] = ++cnt;
	if(j==(n+1)/2)
	{
		bool go = true;
		while(i<top)
		{
			a[i][j] = ++cnt;
			++i;
			--j;
			go = false;
		}
		if(go)
			a[i][j] = ++cnt;
		go = true;
	}
	f(top-1, bottom-2);
	return;
}

int main(void)
{	
	int top, bottom, i, j;
	for(i=0; i<26; ++i)
		for(j=0; j<50; ++j)
			a[i][j] = 0;
	scanf("%d", &n);
	bottom = n;
	top = (1 + bottom) / 2;
	f(top, bottom);
	for(i=1; i<=(n+1)/2; ++i)
	{
		for(j=1; j<=n; ++j)
		{
			if(a[i][j]==0)
				printf("    ");
			else
				printf("%4d", a[i][j]);
		}
		putchar('\n');
	}
	return 0;
}


可以参数一下

您好,我是有问必答小助手,您的问题已经有小伙伴解答了,您看下是否解决,可以追评进行沟通哦~

如果有您比较满意的答案 / 帮您提供解决思路的答案,可以点击【采纳】按钮,给回答的小伙伴一些鼓励哦~~

ps:问答VIP仅需29元,即可享受5次/月 有问必答服务,了解详情>>>https://vip.csdn.net/askvip?utm_source=1146287632

非常感谢您使用有问必答服务,为了后续更快速的帮您解决问题,现诚邀您参与有问必答体验反馈。您的建议将会运用到我们的产品优化中,希望能得到您的支持与协助!

速戳参与调研>>>https://t.csdnimg.cn/Kf0y

这里有一个相同问题: 请查看是否对问题有帮助~
https://ask.csdn.net/questions/7423893