1

嗨,我对 c# 编程相当陌生,所以请多多包涵。我目前正在开发一个“简单”的小程序,它允许用户在同一个文本框中输入 25 个值,一旦完成,我希望能够在列表框中将这 25 个值显示为 5 的数组按 5 列行,我想找出数组中的最大数。

private void button1_Click(object sender, EventArgs e)
{
    int arrayrows = 5;
    int arraycolomns = 5;
    int[,] arraytimes;
    arraytimes = new int[array rows, array columns];

    // list_Matrix.Items.Add(tb_First.Text);
    for (int i = 0; i != 5; i++)
    {
        for (int j = 0; j != 5; j++)
        {
            array times [i,j]= Convert. To Int32(Tb_First.Text);
            list_Matrix.Items.Add(array times[i, j].To String());
        }
    }
}

这是我尝试在列表框中显示数组的方法,但它不起作用。这也使我无法转到下一部分来查找其中最大的数字。

4

3 回答 3

0

您可以使用 .Split(' ') (或任何其他字符或字符串)拆分字符串。这将为您提供一个包含 25 个元素的一维数组(如果已输入所有内容)。将其转换为二维数组或网格的技巧是使用整数除法和模数,以下代码将

String[] splitText = textBox.Text.Split(' '); //gets your 25-length 1D array

//make an empty grid with the right dimensions first
int[][] grid = new int[5][];
for (int i=0;i<5;i++) {
    grid[i] = new int[5];
}

//save our highest value
int maxVal = 0;
//then fill this grid
for (int i=0;i<splitText.Length;i++){
    int value = int.Parse(splitText[i]);
    //i%5 gives us values from 0 to 4, which is our 'x-coordinate' in the grid
    //i/5 uses integer division so its the same as Math.floor(i/5.0), giving us your 'y-coordinates'
    grid[i%5][i/5] = value;

    //check if this value is larger than the one that is currently the largest
    if (value > maxVal)
    {
        maxVal = value;
    }       
}

这将使用拆分的文本框文本填充二维网格数组,如果文本框中没有足够的值,则会在这些单元格中留下 0。

最后,您还将获得最大价值。

于 2013-06-05T07:13:08.520 回答
0

尝试以下操作(通过将数字打印为字符串来显示)。并假设您按以下方式输入数字,

'1,2,3,4...'

string[] nums=txtBox.Text.Split(',');
lstBox.Items.Clear();
int colCount=5;
int colIndex=0;
string line="";
foreach(string num in nums)
{
   if(colIndex==colCount)
   {
     lstBox.Items.Add(line);
     line="";
     colIndex=0;
   }
   line+= line==""? num : " "+num;
   colIndex+=1;
}
if(line!="")
   lstBox.Items.Add(line);

确保更正任何语法错误,并将参数名称更改为您的。

于 2013-06-05T08:05:15.577 回答
0
private void button1_Click(object sender, EventArgs e)
        {
            int[] ab=new int[10];
            string s = textBox1.Text;
            int j = 0;


            string [] a = (s.Split(' '));
            foreach (string  word in a)
            {
                ab[j] = Convert.ToInt32(word);
                j++;
            }


            for (int i = 0; i < 10; i++)
            {
                label2.Text +=ab[i].ToString()+" ";
            }
        }
于 2015-10-19T07:19:37.043 回答