我需要帮助在单独的方法中访问数组的特定值。在这个程序中,我应该写一个程序,要求用户输入一个日历年的每个月的降雨量。然后,该程序将确定年度和月平均降雨量,并最终允许用户搜索特定数量。
我应该为最后一个方法执行此操作:SearchForAmounts()
- 此方法将是一个void方法,并为参数提供两个double数组
list,一个用于降雨量数组,一个用于带有月份的数组。它将要求用户在阵列中搜索降雨量。然后,它将报告在哪个月首次下跌或将会出现的数额
报告说那一年没有降雨量。它将使用Array类方法之一来确定要输出的内容。它会在方法中执行两次 - 即在方法中重复两次代码。
我在找到一种方法来访问monthInTheYear
数组中的值时遇到了麻烦。这是我的代码:
namespace CJohnson_Prog8
{
class Program
{
static void Main(string[] args)
{
string[] monthInTheYear;
double[] rainfallAmmounts;
monthInTheYear = new string[12] { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
rainfallAmmounts = new double[12];
Console.WriteLine("Welcome to the Annual Rainfall Program");
GetRainFall(rainfallAmmounts, monthInTheYear);
PrintAmounts(rainfallAmmounts, monthInTheYear);
TotalYearRain(rainfallAmmounts);
SearchForAmounts(rainfallAmmounts, monthInTheYear);
}
public static void GetRainFall(double[] rainfall, string[] month)
{
for (int i = 0; i < rainfall.Length; i++)
{
Console.Write("Enter the rainfall in inches in {0}: ", month[i]);
rainfall[i] = double.Parse(Console.ReadLine());
while (rainfall[i] < 0)
{
Console.Write("Enter the rainfall in inches in {0}: ", month[i]);
rainfall[i] = double.Parse(Console.ReadLine());
}
}
}
public static void PrintAmounts(double[] rainfall, string[] month)
{
for (int i = 0; i < rainfall.Length; i++)
{
Console.WriteLine("{0}\t\t{1:F2}", month[i], rainfall[i]);
}
}
public static double TotalYearRain(double[] totalrainFall)
{
double averageRainFall;
double sum = 0;
for (int i = 0; i < totalrainFall.Length; i++)
{
sum += totalrainFall[i];
}
averageRainFall = sum / 12;
Console.WriteLine("");
Console.WriteLine("Total Annual Rain is: {0:F2}", sum);
Console.WriteLine("Average Month Rain: {0:F2}", averageRainFall);
return sum;
}
public static void SearchForAmounts(double[] searchRainFall, string[] searchMonths)
{
Console.Write("Enter a rainfall amount to search for: ");
double RainFall = double.Parse(Console.ReadLine());
if (Array.IndexOf(searchRainFall, RainFall) != 1)
{
Console.WriteLine(searchMonths[i] + " was the first month to have " + RainFall + " inches fell this year.");
}
else
{
Console.WriteLine("No rainfall of " + RainFall + " inches fell that year.");
}
}
}
}
答案 0 :(得分:0)
for (int i = 0; i <= 1; i++) {
//do stuff
var index = Array.IndexOf(searchRainFall, RainFall);
if (index > -1) {
Console.WriteLine(searchMonths[index] + " was the first month to have " + RainFall + " inches fell this year.");
} else {
Console.WriteLine("No rainfall of " + RainFall + " inches fell that year.");
}
}