问题是这样的。我固定一个数组的列数,然后根据数字编号来确定它处于多少行多少列。
如:
1 2 3 4 5 6
7 8 9 10 11 12
13 14 15 16 17 18
19 20 21 22 23 24
数组的行数不固定,但列数是固定的,比如16,它处于第3行第4列。我用常规for循环写了如下代码:using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;namespace ConsoleApplication1
{
class Program
{
public void GetLocation(uint numberCount, uint columnCount)
{
for (int i = 1; i <= columnCount; i++)
{
for (int j = 1; j <= numberCount / columnCount + 1; j++)
{
if ((j - 1) * columnCount + i == numberCount)
{
Console.WriteLine("数字{0}位于第{1}行第{2}列.", numberCount, j, i);
}
}
}
} static void Main(string[] args)
{
Console.WriteLine("请输入数字编号:");
uint numberCount = uint.Parse(Console.ReadLine());
Console.WriteLine("请输入列数:");
uint columnCount = uint.Parse(Console.ReadLine());
Program p = new Program();
p.GetLocation(numberCount, columnCount);
Console.ReadLine();
}
}
}如果用递归,该怎么写呢?
如:
1 2 3 4 5 6
7 8 9 10 11 12
13 14 15 16 17 18
19 20 21 22 23 24
数组的行数不固定,但列数是固定的,比如16,它处于第3行第4列。我用常规for循环写了如下代码:using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;namespace ConsoleApplication1
{
class Program
{
public void GetLocation(uint numberCount, uint columnCount)
{
for (int i = 1; i <= columnCount; i++)
{
for (int j = 1; j <= numberCount / columnCount + 1; j++)
{
if ((j - 1) * columnCount + i == numberCount)
{
Console.WriteLine("数字{0}位于第{1}行第{2}列.", numberCount, j, i);
}
}
}
} static void Main(string[] args)
{
Console.WriteLine("请输入数字编号:");
uint numberCount = uint.Parse(Console.ReadLine());
Console.WriteLine("请输入列数:");
uint columnCount = uint.Parse(Console.ReadLine());
Program p = new Program();
p.GetLocation(numberCount, columnCount);
Console.ReadLine();
}
}
}如果用递归,该怎么写呢?
{
Console.WriteLine("数字{0}位于第{1}行第{2}列.", numberCount, numberCount / columnCount + 1, numberCount % columnCount);
}
private int[,] test=new int[20,30];
private int targetNumber=20;//找到数字20的位置public Ponint GetLocationY(uint x) //X为第一维上限,可以用test.getUp***(0)获得
{
if(x==-1) return null; //没有找到
int y=this.GetLocationY(x,test.getUp***(1)-1);
if(y!=-1) return new point(x,y);
this.GetLocationX(x--)
}public int GetLocationY(uint x,uint y) //Y为第二维上限,可以用test.getUp***(1)获得
{
if(y==-1) return -1;
if(test[x,y]==targetNumber) return y;
this.GetLocationY(x,y--);
}递归就是不断的通过自己调用自己,并自己在达到某种程序时跳出递归
{
uint col = numberCount % columnCount;
Console.WriteLine("数字{0}位于第{1}行第{2}列.", numberCount, col == 0 ? numberCount / columnCount : numberCount / columnCount + 1, col == 0 ? columnCount : col);
}