我是一個相當新的 C#,我想做的是用 for 回圈中的其他陣列的值填充空陣列。如果第一個陣列的值滿足第二個陣列的要求,則將其填充。
int[] cisla = new int[] {a, b, c, d, e, f}; //first array
int[] nadprumer = new int[] {}; //second array
decimal prumer = (a b c d e f) / 6;
for (int i = 0; i< cisla.Length; i )
{
if (cisla[i] > prumer)
{
//join value into "nadprumer" array
}
}
uj5u.com熱心網友回復:
看起來你正在做家庭作業或你閱讀的書中的某種練習。如果他們要求你找出所有大于他們平均值的數字,那么我會這樣做。
第一個變體(帶回圈的基本級別):
int[] cisla = new int[] { 1, 2, 3, 4, 5, 6 }; //first array
double prumer = cisla.Average();
List<int> temp = new List<int>();
for (int i = 0; i < cisla.Length; i )
{
if (cisla[i] > prumer)
{
temp.Add(cisla[i]);
}
}
int[] nadprumer = temp.ToArray(); //second array
第二種變體(LINQ 高級):
int[] cisla = new int[] { 1, 2, 3, 4, 5, 6 }; //first array
double prumer = cisla.Average();
int[] nadprumer = cisla.Where(x => x > prumer).ToArray();
uj5u.com熱心網友回復:
像上面提到的那樣分配一個 List 型別會更好 - 但它就在這里。也許這會有所幫助?
static void Main(string[] args)
{
int[] cisla = new int[] { 1, 2, 3, 4, 5, 6 }; //first array type int cannot be strings or characters
int[] nadprumer = new int[6] ; //second array needs initialized
decimal prumer = (cisla[0] cisla[1] cisla[2] cisla[3] cisla[4] cisla[5]) / 6;//why do you need this?
for (int i = 0; i < cisla.Length; i )
{
//if (cisla[i] > prumer)//why are you doing this?
//{
//join value into "nadprumer" array
nadprumer[i] = cisla[i];
Console.WriteLine(nadprumer[i]);
//}
}
Console.ReadLine();
}
uj5u.com熱心網友回復:
你的代碼:
int[] nadprumer = new int[] {};
將創建一個長度為 0 的陣列。
你需要做的是:
int[] nadprumer = new int[cisla.Length];
然后在你的回圈中:
nadprumer[i] = cisla[i];
但這會將其余部分保留為 0。如果您不希望這樣,請創建 aList<int>作為目標,然后擁有
theList.Add(cisla[i]);
在回圈中,如果您需要將結果作為陣列,請在最后將其更改為陣列,如下所示:
theList.ToArray();
轉載請註明出處,本文鏈接:https://www.uj5u.com/yidong/433022.html
