[英]Creating a new one-dimensional array from all positive elements of each row of a two-dimensional dynamic array in c#
我是一個新手程序員,所以有一些問題。 該程序僅顯示一維數組中的 3 個正元素,盡管二維數組中可能有更多元素。
這是我的代碼
using System;
namespace task_2
{
class arrays
{
public int[,] A = new int[3, 3];
public int[] B = new int[9];
public void two_dimensional_array()
{
Random rand = new Random();
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
A[i, j] = rand.Next(-100, 100);
}
}
Console.WriteLine("Two-dimensional array: ");
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
Console.Write("{0}\t", A[i, j]);
}
Console.WriteLine();
}
}
public void one_dimensional_array()
{
Console.WriteLine("\nA one-dimensional array with only positive elements: ");
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
if (A[i, j] > 0)
B[i] = A[i, j];
}
}
for (int i = 0; i < 9; i++)
{
Console.WriteLine(B[i]);
}
}
}
class Program
{
static void Main()
{
Console.OutputEncoding = System.Text.Encoding.Default;
arrays a;
a = new arrays();
a.two_dimensional_array();
a.one_dimensional_array();
}
}
}
我在下面附上了結果的照片,其中只顯示了三個積極因素:在此處輸入圖片描述
將此行編輯為:(如果您希望zero to be displayed instead of negative
)
//B[i] = A[i, j];
B[i*3+j] = A[i, j];
如果你不想negative numbers not to be displayed
:
int index=0;
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
if (A[i, j] > 0)
B[index++] = A[i, j];
}
}
for (int i = 0; i < index; i++)
{
Console.WriteLine(B[i]);
}
在您的方法one_dimensional_array()
中,您使用嵌套for
循環來檢查A
中的所有項目並有條件地更新B
中的項目:
for (int i = 0; i < 3; i++)
{
for (int j = 0; j < 3; j++)
{
if (A[i, j] > 0)
B[i] = A[i, j];
}
}
使用i
和j
迭代A
的項目如您所料:您循環遍歷三行和三列。
您使用i
遍歷B
的索引的方式阻止您遍歷B
的所有索引。 您實際上只是在索引 0、1 和 2 上循環(根據您在外部for
循環中i
的可能范圍的說明)。
在您的嵌套循環中,您將點擊if (A[i, j] > 0)
行九次。 i
、 j
、 A[i, j]
和B[i]
的值將更改如下:
| i | j | A[i, j] | B[i] |
|-----|-----|-----------|--------|
| 0 | 0 | A[0, 0] | B[0] |
| 0 | 1 | A[0, 1] | B[0] |
| 0 | 2 | A[0, 2] | B[0] |
|-----|-----|-----------|--------|
| 1 | 0 | A[1, 0] | B[1] |
| 1 | 1 | A[1, 1] | B[1] |
| 1 | 2 | A[1, 2] | B[1] |
|-----|-----|-----------|--------|
| 2 | 0 | A[2, 0] | B[2] |
| 2 | 1 | A[2, 1] | B[2] |
| 2 | 2 | A[2, 2] | B[2] |
因此,
B[0]
被賦予A
中第一行中的最后一個正值(如果該行中的任何值為正)B[1]
被賦予A
中第二行中的最后一個正值(如果該行中的任何值為正)B[2]
被賦予A
中第三行中的最后一個正值(如果該行中的任何值為正) 因此,您需要一種方法來遍歷B
的所有索引(即0
-- 8
)。
可以根據已經存在的i
和j
值計算這樣的參數:
變量 k = f(i, j)
可以按如下方式使用:
B[k] = A[i, j];
你能找出k
的表達式嗎?
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.