数字旋转方阵(c#数组的使用)
2007-04-13 20:40
851 查看
今天上机编了一个小程序,觉得挺有意思的。拿出来和大家一起分享一下。
题目大体意思如下:
根据用户键入的值,输出如下格式的数字旋转方阵。
例:输入4
输出方阵如下:
1 12 11 10
2 13 16 9
3 14 15 8
4 5 6 7
代码如下:
static void Main(string[] args)
{
Console.Write("请输入n的值:");
int n = int.Parse(Console.ReadLine());
int[,] a = new int[n, n];
int i = 0, j = 0;//二维数组的两个下标
int cout = 1;
int m = 0; //当前圈数
;
while (m < n / 2)//依次为每一圈得元素赋值
{
for (i = m, j = m; i < n - m - 1; i++)
a[i, j] = cout++;
for (j = m; j < n - m - 1; j++)
a[i, j] = cout++;
for (i = n - m - 1; i > m; i--)
a[i, j] = cout++;
for (j = n - m - 1; j > m; j--)
a[i, j] = cout++;
m++;
}
if (n % 2 != 0)//n为奇数的情况,为中间元素赋值
a[n / 2 , n / 2 ] = n * n;
Console.WriteLine("该方阵如下所示:");//输出方阵
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
if (a[i, j] < 10)
Console.Write(" {0}", a[i, j]);
else
Console.Write(" {0}", a[i, j]);
}
Console.Write("/n/n");
}
Console.WriteLine("Press Anykey to continue...");
Console.ReadLine();
}
}
}
希望大家能和我多多交流。
题目大体意思如下:
根据用户键入的值,输出如下格式的数字旋转方阵。
例:输入4
输出方阵如下:
1 12 11 10
2 13 16 9
3 14 15 8
4 5 6 7
代码如下:
static void Main(string[] args)
{
Console.Write("请输入n的值:");
int n = int.Parse(Console.ReadLine());
int[,] a = new int[n, n];
int i = 0, j = 0;//二维数组的两个下标
int cout = 1;
int m = 0; //当前圈数
;
while (m < n / 2)//依次为每一圈得元素赋值
{
for (i = m, j = m; i < n - m - 1; i++)
a[i, j] = cout++;
for (j = m; j < n - m - 1; j++)
a[i, j] = cout++;
for (i = n - m - 1; i > m; i--)
a[i, j] = cout++;
for (j = n - m - 1; j > m; j--)
a[i, j] = cout++;
m++;
}
if (n % 2 != 0)//n为奇数的情况,为中间元素赋值
a[n / 2 , n / 2 ] = n * n;
Console.WriteLine("该方阵如下所示:");//输出方阵
for (i = 0; i < n; i++)
{
for (j = 0; j < n; j++)
{
if (a[i, j] < 10)
Console.Write(" {0}", a[i, j]);
else
Console.Write(" {0}", a[i, j]);
}
Console.Write("/n/n");
}
Console.WriteLine("Press Anykey to continue...");
Console.ReadLine();
}
}
}
希望大家能和我多多交流。
相关文章推荐
- 旋转数组的最小数字
- 使用C#,不使用任何Parse,TryParse,Convert方法,将数字字符串转换成整数
- 寻找数字在旋转数组中的位置
- 数字旋转方阵 分治法
- 旋转数组的最小数字
- 剑指Offer:旋转数组的最小数字
- 剑指offer编程题——08 旋转数组中的最小数字
- 剑指offer(6)-旋转数组的最小数字
- P66、面试题8:旋转数组的最小数字
- 旋转数组的最小数字
- 旋转数组中的最小数字
- 对数组使用 foreach(C# 编程指南)
- 17.剑指offer-旋转数组的最小数字
- 旋转数组的最小数字
- 【每日面试题】使用递归方法判断数字是否是升序数组
- C#项目使用Properties.Settings保存数组
- 剑指Offer----面试题八:旋转数组的做小数字
- .NET复习第二天 练习数字交换,字符串转换 求数组最大值 快捷键的使用
- (剑指offer)旋转数组的最小数字
- C#创建数字证书并导出为pfx,并使用pfx进行非对称加解密