简体   繁体   中英

Why my code isn't displaying last writeline

class Program
{
    static void Main(string[] args)
    {
        int[] massiiv = new int[20];
        int sum = 0;
        Random r = new Random();

        for (int arv = 1; arv <= 20; arv++)
        {
            if (massiiv[arv] % 2 == 0)
                sum = sum + massiiv[arv];

            Console.WriteLine("{0}", r.Next(100, 200));
        }

        Console.WriteLine("{0}", sum);
        Console.ReadKey();
    }
}

So I want to display sum of even numbers in my array, but the WriteLine isn't displaying at all. I need to form a one dimension array consisting of 20 random ints between 100 and 200 and I want console to print sum of all even numbers in array.

you see, when you create an array, that does not put numbers in the array. if you want the array to be filled with number, you should initiate the array with numbers. if you want random numbers, you should put random numbers in it.

you did

Random r = new Random();

that initiate a Random class but does nothing to the array massiiv

you need to put random numbers in the array like so:

for (int arv = 1; arv <= 20; arv++)
{
   massiiv[arv] = r.NextInt(100) + 100;
}

that will put random numbers in the array

r.NextInt(100)

create a random number between 0-100, and so

r.NextInt(100) + 100

create a random number between 100-200

You array consists of 20 zeros. Also this code throws exception because there is no massiiv[20] element. Array with 20 elements has indexes 0-19. It should be for (int arv = 0; arv < 20; arv++)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM