1.08 KB, 阅读权限: 100, 下载次数: 1
代码
运行结果.PNG (2.88 KB, 下载次数: 0)
n=5的运行结果
123.jpg (28.74 KB, 下载次数: 0)
WWW.png (11.4 KB, 下载次数: 0)
1.02 KB, 阅读权限: 100, 下载次数: 1
F2}DN~5T16Z67TLM_`VXNZU.jpg (16.08 KB, 下载次数: 0)
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace 数组的题
{
class Program
{
static void Main(string[] args)
{/*
思想:如果我们求的二维数组的行数是偶数,那么一个外围中大小一个是这样的
* 下边→右边→上边→左边 例如:行数是4的数的二维数组
* 7 8 9 10
* 6 1 2 11
* 5 4 3 12
* 16 15 14 13
* 他们从大到小是 16 15 14 → 13 12 11 → 10 9 8 → 7 6 5
* 用这种方式一层一层的给二位数组赋值
*
*
如果我们求的二维数组的行数是奇数数,那么一个外围中大小一个是这样的
* 上边→左边→下边→右边 例如:行数是3的数的二维数组
* 7 8 9
* 6 1 2
* 5 4 3
* 他们从大到小是 9 8 → 7 6 → 5 4 → 3 2
* 用这种方式一层一层的给二位数组赋值
*/Console.WriteLine("输入一个数");
//转换为int型
int num =Convert.ToInt32( Console.ReadLine());
//定义数组
int[,]shuzu = new int[num,num];int xxh = num-1; //用去记住我们要循环的开始位置和结束位置
int num1 = num; //用于求最大值
//循环的次数是行数的一半
for (int w = (num + 1) / 2; w >= 1; w--)
{
#region 偶数
if (num % 2 == 0)
{
//本次循环的最大值
int zuida = num1 * num1;//下边
for (int j = num - 1 - xxh; j < xxh; j++)
{//下边:从左往右赋值 依次减小1
shuzu[xxh, j] = zuida;
zuida--;
}//右边
for (int j = xxh; j > num - 1 - xxh; j--)
{//右边:从下往上赋值 依次减小1
shuzu[j, xxh] = zuida;
zuida--;
}//上面
for (int j = xxh; j > num - 1 - xxh; j--)
{ //上边:从右往左赋值 依次减小1
shuzu[num - 1 - xxh, j] = zuida;
zuida--;
}//左边
for (int j = num - 1 - xxh; j < xxh; j++)
{//左边:从上往下赋值 依次减小1
shuzu[j, num - 1 - xxh] = zuida;
zuida--;
}
xxh--; //开始和结束位置向中间靠拢
num1 = num1 - 2; //前一个和后一个偶数相差2
}
#endregion#region 奇数
/*和偶数的循环同理 只是 他的大小事这样的: 上边→左边→下边→右边*/
if (num % 2 == 1)
{
int zuida = num1 * num1;
//上面一行
for (int j = xxh; j >= num - 1 - xxh; j--)
{
shuzu[num - 1 - xxh, j] = zuida;
zuida--;
}
//最左边
zuida++;
for (int j = num - 1 - xxh; j < xxh; j++)
{
shuzu[j, num - 1 - xxh] = zuida;
zuida--;
}//最后一行
for (int j = num - 1 - xxh; j <= xxh; j++)
{
shuzu[xxh, j] = zuida;
zuida--;
}//最右边这排
zuida++;
for (int j = xxh; j > num - 1 - xxh; j--)
{
shuzu[j, xxh] = zuida;
zuida--;
}xxh--;
num1 = num1 - 2;}
#endregion}
//这个for是显示第一行的*号的
for (xxh = 0; xxh < num+2; xxh++)
{
Console.Write("*\t");
}//这个for是显示数据和显示数据前面和后面的*
for (int k = 0; k < num; k++)
{
Console.WriteLine();
Console.WriteLine();
Console.Write("*\t");
for (int l = 0; l < num; l++)
{
Console.Write("{0}\t",shuzu[k, l]);
}
Console.Write("*");
}//数据完成后,换一哈行
Console.WriteLine("\n\t");//这个for是显示最后一行的*号的
for ( xxh = 0; xxh < num + 2; xxh++)
{
Console.Write("*\t");
}Console.ReadKey();
}
}
}
欢迎光临 黑马程序员技术交流社区 (http://bbs.itheima.com/) | 黑马程序员IT技术论坛 X3.2 |