[英]Out of bounds with array index in C#
基本上,我需要编写一个程序来计算x年内每月的平均降雨量。 我希望它询问用户多少年,然后使用for循环遍历所有月份,最后计算平均降雨量。 但是运行时出现错误
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();
}
}
}
在for
循环中,您希望有12个月,但是在您的几个月中,您只有11个月-缺少9月。 添加它,一切都应该正常工作:
string[] months = {"January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.