C#中的数组索引越界

本文关键字:索引 越界 数组 | 更新日期: 2023-09-27 18:24:55

基本上我需要编写一个程序来计算x年内每月的平均降雨量。我希望它能询问用户在所有月份使用循环的年数,并在最后计算平均降雨量。但我运行时出错了

Rainfall.exe 中发生类型为"System.IndexOutOfRangeException"的未处理异常

我认为发生的情况是,在内部for循环完成后,y被设置为12,这使得数组越界,但我认为,一旦外部数组完成每个循环,内部的y变量就会重置为0。

有人能解释一下吗?

using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
namespace Rainfall
{
   class Program
   {
     static void Main(string[] args)
     {
        Console.WriteLine("This program will calculate the average amount of rainfall per month over the course of x years. ");
        Console.WriteLine();
        double years = 0;
        Console.WriteLine("Over how many years will this calculation take place?");
        years = int.Parse(Console.ReadLine());
        string[] months =  {"January", "February", "March", "April", "May", "June", "July", "August", "October", "November", "December" };
        double totalRainfall = 0;
        double monthRain = 0;
        double totalMonths = 0;
        double averageRainfall = 0;
        for (int x = 0; x < years; x++)
        {
            for(int y = 0; y < 12; y++)
            {
                Console.WriteLine("Enter the rainfall for the month of {0}", months[y]);
                monthRain = int.Parse(Console.ReadLine());
                totalRainfall = totalRainfall + monthRain;
            }
        }
        averageRainfall = totalRainfall / totalMonths;
        Console.WriteLine("The average rainfall per month is " + averageRainfall);
        Console.ReadLine();
     }
   }
}

C#中的数组索引越界

在您的for循环中,您预计会有12个月,但在您的月份数组中,您只有11个月——缺少9月。加上它,一切都应该很好:

string[] months =  {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };