用 for 循环中的值填充数组

Fill array with values from for loop

我是 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
        }      
    }

像上面提到的那样分配 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();
        }

您的代码:

int[] nadprumer = new int[] {};

将创建一个长度为 0 的数组。

您需要做的是:

int[] nadprumer = new int[cisla.Length];

然后在你的循环中:

nadprumer[i] = cisla[i];

但这会将其余部分保留为 0。如果您不想这样,请创建一个 List<int> 作为目标,然后让

theList.Add(cisla[i]); 

在循环中,如果你需要结果是一个数组,那么在最后把它改成一个数组,像这样:

theList.ToArray();

看起来您正在做作业或您阅读的书中的某种练习。如果他们要求你找到所有大于他们的平均值的数字,那么我会这样做。

第一个变体(带循环的基础水平):

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();