C#-有关for循环的问题.索引超出数组范围-为什么程序不中断for循环并继续 [英] C# - issues with for loop. index outside of bounds of array - Why the program doesn't break out of for loop and continue

查看:140
本文介绍了C#-有关for循环的问题.索引超出数组范围-为什么程序不中断for循环并继续的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我的问题是我想在for循环后打印出信息,但它从未真正到达代码.是否有特定原因,还是应该将所有内容都放入for循环的范围内?数组键之外的索引

`int sumEven=1, sumOdd=1;
            Console.WriteLine("Give the amount of numbers:  ");
            int amount = int.Parse(Console.ReadLine());
            Console.WriteLine("Numbers:  ");
            int[] numberInputs = new int [amount];
            for (int inc = 1; inc <= amount; inc++)
            {
                numberInputs[inc] = int.Parse(Console.ReadLine());
                if (inc % 2 == 0)
                {
                    sumEven *= numberInputs[inc];
                }
                else
                {
                    sumOdd *= numberInputs[inc];
                }
            }
            if (sumEven == sumOdd)
            {
                Console.WriteLine("Yes\n");
                Console.Write($"Product = {sumEven}");
            }
            else if (sumEven != sumOdd)
            {
                Console.Write("No\n");
                Console.WriteLine($"Even product = {sumEven}");
                Console.WriteLine($"Odd product = {sumOdd}");
            }

推荐答案

尝试使用inc<数量,而不是inc< =数量

try to use inc < amount instead of inc <= amount

for (int inc = 0; inc < amount; inc++)
        {
            numberInputs[inc] = int.Parse(Console.ReadLine());
            if (inc % 2 == 0)
            {
                sumEven *= numberInputs[inc];
            }
            else
            {
                sumOdd *= numberInputs[inc];
            }
        }

for (int inc = 1; inc < amount; inc++)
        {
            numberInputs[inc] = int.Parse(Console.ReadLine());
            if (inc % 2 == 0)
            {
                sumEven *= numberInputs[inc];
            }
            else
            {
                sumOdd *= numberInputs[inc];
            }
        }

我还建议您通过 IndexOutOfRangeException

这篇关于C#-有关for循环的问题.索引超出数组范围-为什么程序不中断for循环并继续的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆