Domanda

I am stuck, I am trying to write a code that displays the first positive odd number in my index. For some reason its not doing it. It just display whatever the first number is in my index. What am I doing wrong. I new so if you could help me I be very thank full. Also if you could keep is simple too thanks.

static void Main(string[] args)
{
    int[] A = { -2, 5, -1, 9, -6, 23, 67, 1, -8, 7, -3, 90 };
    int index = FirstPosOddNum(A);
    if (index >= 0)
    {
        Console.WriteLine("The first Positive value is: {0}, In Index {1}",
            A[index], index);
    }
    else
    {
        Console.WriteLine("No positive odd value available.");
    }
    Console.ReadLine();
}
static int FirstPosOddNum(int[] array)
{
    for (int i = 0; i < array.Length; i++)
    {
        if ((array[i] % 2 == 1) || (array[i] % 2 == -1))
            return i;
    }
    return -1;
}
È stato utile?

Soluzione

Change this:

if ((array[i] % 2 == 1) || (array[i] % 2 == -1))

To this:

if ((array[i] > 0) && (array[i] % 2 == 1))

You want to find the first positive and odd number, which is exactly what the condition in the if says.

Altri suggerimenti

Try this:

static void Main(string[] args)
    {
        int[] A = { -2, 5, -1, 9, -6, 23, 67, 1, -8, 7, -3, 90 };
        int index = FirstPosOddNum(A);
        if (index >= 0)
        {
            Console.WriteLine("The first Positive value is: {0}, In Index {1}",
                A[index], index);
        }
        else
        {
            Console.WriteLine("No positive odd value available.");
        }
        Console.ReadLine();
    }
    static int FirstPosOddNum(int[] array)
    {
        for (int i = 0; i < array.Length; i++)
        {
            if (array[i] % 2 == 1)
                return i;
        }
        return -1;
    }

A some of your comments said, you need to remove from your code your array[i] % 2 == -1

I compiled and ran your code. It is not having the problem you described. It is working as you want it to:

displays the first positive odd number in my index

Maybe sure you Rebuild-All and are running the code you actually are seeing.

Also, make the change the other answer suggests.

You could simply say:

static int FirstPosOddNum(int[] array)
{
    int value = -1 ;
    for ( int i = 0; value < 0 && i < array.Length; ++i )
    {
      int x = array[i] ;
      if ( x > 0 && 0 != (x&1) ) value = x ;
    }
    return -1;
}

Or (even simpler):

static int FirstPosOddNum(int[] array)
{
    int v = array.FirstOrDefault( x => x > 0 && 0 != (x&1) ) ;
    return v > 0 ? v : -1 ;
}
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top