[英]In C#, How can I iterate through a entire 2D Array and count the number of 0s?
[英]How could I iterate through a 2D array, double each number, then print the updated array?
正如問題所說,我正在嘗試通過每個數字獲取下面列出的數組和 go,將數字加倍,並將新數字返回到數組,完成后,調用打印新數組的方法。 我最初的想法是,也許我可以通過行/列 go 並以這種方式獲得數字,乘以 2,然后返回它,但有人告訴我一些類似於 int 不能轉換為 int[ , ]. 我似乎無法弄清楚從這里到 go 的位置。
int[,] array_2d = {{1, 2, 3},{ 4, 5, 6},{7, 8, 9}};
public static int[ , ] DoubleArray(int[ , ] array_2d){
for (int row = 0; row < 3; row++){
for (int col = 0; col < 3; col ++){
int val = array_2d[row,col];
return val * 2;
}
}
}
還要澄清一下,數組在 main 方法中,而這是一個單獨的方法,需要在 main 中以數組作為參數調用。
提前致謝!
我認為你可以這樣做:
public static int[,] DoubleArray(int[,] array_2d)
{
for (int row = 0; row < 3; row++)
{
for (int col = 0; col < 3; col++)
{
array_2d[row, col] = array_2d[row, col] * 2;
}
}
return array_2d;
}
public static void PrintArray(int[,] array_2d)
{
for (int row = 0; row < 3; row++)
{
for (int col = 0; col < 3; col++)
{
Console.Write($"{array_2d[row, col]} ");
}
}
}
public static void Main(string[] args)
{
int[,] array_2d = { { 1, 2, 3 }, { 4, 5, 6 }, { 7, 8, 9 } };
var doubledArray = DoubleArray(array_2d);
PrintArray(doubledArray);
}
與 int 相關的錯誤的原因是您 state 返回類型為“int[,]”,然后在返回語句中,您試圖返回類型為“int”的值。 為了解決這個問題,您需要返回一個由您的返回類型指定的 2d int 數組。 我還建議動態獲取數組的長度,而不是在這三個中進行硬編碼。 下面的代碼應該可以完成這項工作。
public static int[,] DoubleArray(int[,] array_2d)
{
for (int row = 0; row < array_2d.GetLength(0); row++)
{
for (int col = 0; col < array_2d.GetLength(1); col++)
{
int val = array_2d[row, col];
array_2d[row, col] = val * 2;
}
}
}
return array_2d;
}
編輯:正如@hijinxbassist 指出的那樣,這將修改原始數組,如果您想保留原始數組的值,則可以使用下面稍作改動的 function。
public static int[,] DoubleArray(int[,] array_2d)
{
int[,] newArray = (int[,])array_2d.Clone();
for (int row = 0; row < newArray.GetLength(0); row++)
{
for (int col = 0; col < newArray.GetLength(1); col++)
{
int val = newArray[row, col];
newArray[row, col] = val * 2;
}
}
}
return newArray;
}
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.