输出对数组求平均值的结果时出现问题
本文关键字:问题 结果 数组 平均值 输出 | 更新日期: 2023-09-27 18:15:49
using System;
namespace RainfallHW {
class Program {
static void Main(string[] args) {
string [] months;
double[] rain;
months = new string [12] { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
rain = new double[12];
for (int i = 0; i < rain.Length; i++) {
Console.Write("Rainfall in {0}: ", months[i]);
rain[i] = double.Parse(Console.ReadLine());
while (rain[i] < 0) {
Console.Write("Rainfall in {0}: ", months[i]);
rain[i] = double.Parse(Console.ReadLine());
double avg;
double sum = 0;
for (int x = 0; x < rain.Length; x++) {
sum = sum + rain[i];
}
avg = sum / 12;
Console.WriteLine("");
Console.WriteLine("Average Month Rain: ", avg);
}
}
}
}
}
我正试着把每个月的降雨量计算出来,然后取平均值。我无法让它打印出我的平均分结果。我对数组和循环比较陌生,我只是不太确定我在这里哪里出错了。
我目前没有得到任何输出。一旦输入每个月的输入,程序就会关闭。
你显然把花括号弄乱了。avg计算块移动到正确位置后,开始工作:
string [] months;
double[] rain;
months = new string [12] { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December"};
rain = new double[12];
for (int i = 0; i < rain.Length; i++) {
Console.Write("Rainfall in {0}: ", months[i]);
rain[i] = double.Parse(Console.ReadLine());
while (rain[i] < 0) {
Console.Write("Rainfall in {0}: ", months[i]);
rain[i] = double.Parse(Console.ReadLine());
}
}
double avg;
double sum = 0;
for (int i = 0; i < rain.Length; i++) {
sum = sum + rain[i];
}
avg = sum / 12;
Console.WriteLine("");
Console.WriteLine("Average Month Rain: " + avg);
您已经非常接近了:将降雨量相加并除以月数的代码必须在读取循环之后执行,而不是在其中执行。
目前您不打印任何内容,因为校正负输入的循环包含了打印平均值的代码。
你可以做加法来计算sum
。下面是你可以做的一个大纲:
- 创建一个贯穿12个月的
for
循环 - 查询雨量
- 当输入的值为负时,继续要求输入
- 当输入非负值时,将该值加到运行总数中
- 一旦读取循环完成,打印运行总数除以12。
EDIT:请考虑我对下面代码的编辑。更新的while
循环应该确保提供一个实际的数字。对于现有的while循环,如果输入的不是数字,就会抛出异常。
问题是你的while
循环内的代码。这看起来像是在说"嘿,你没有输入有效的数字,再试一次"这很好,但是其余的代码也在这个循环中。
:
using System;
namespace RainfallHW
{
class Program
{
static void Main(string[] args)
{
string[] months;
double[] rain;
double avg;
double sum = 0;
double value;
string input;
bool isValid = false;
months = new string[12] { "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" };
rain = new double[12];
for (int i = 0; i < rain.Length; i++)
{
Console.Write("Rainfall in {0}: ", months[i]);
while (!isValid)
{
input = Console.ReadLine();
//TryParse returns true if input is a number
//Then check for > 0
if (double.TryParse(input, out value) && double.Parse(input) > 0)
{
rain[i] = double.Parse(input);
sum += rain[i]; //update the sum here instead of its own loop
isValid = true;
}
else
{
Console.Write("Rainfall in {0}: ", months[i]);
}
}
}
avg = sum / 12;
Console.WriteLine("");
Console.WriteLine("Average Month Rain: {0}", avg);
}
}
}
这就是我从认为你想要做的事情中得到的。如果不是这样,请告诉我,我可以再看一看。
现在的运行方式为
Get Input for month
Check for invalid input
Loop through final month
Loop through rain array to compute average *annual* rainfall