質問

Hi guys I got a small problem for some reason I got an error on my sum. and however and where ever I put my int sum; it wont fix the error.

static void TotalOfEvenNegatives(int[] array)
{
    for (int i = 0; i < array.Length; i++)
    {
        if (array[i] % 2 == 0 && array[i] < 0)
        {
            int sum;
            sum += array[i];
        }
    }
}
役に立ちましたか?

解決

static void TotalOfEvenNegatives(int[] array)
{
    int sum = 0;
    for (int i = 0; i < array.Length; i++)
    {
        if (array[i] % 2 == 0 && array[i] < 0)
        {

            sum += array[i];
        }
    }
}

You need to initialise it outside the loop and set it to 0. By setting it inside the loop, you are overriding it every iteration so it can never increment.

他のヒント

You are declaring sum inside your loop, thus overwriting all the values, declare it outside.

static int TotalOfEvenNegatives(int[] array)
{
    int sum = 0; //HERE

    for (int i = 0; i < array.Length; i++)
    {
        if (array[i] % 2 == 0 && array[i] < 0)
        {
            sum += array[i];
        }
    }
    return sum;
}

Also your method should return sum and you can use it like:

int total = TotalOfEvenNegatives(new [] {1,2,3,4,}; //ClassName.TotalOfEvenNegatives

Do not forget to initialize the sum with 0 otherwise you will get the error "Use of unassigned variable"

Why not do it the simple way:

      int[] myArray = {1,2,3,4,} ;
      int   sum     = myArray.Where( x => x < 0 && 0 == x % 2 ).Sum() ;
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top