gpt4 book ai didi

c# - 无法打印出平均数组的结果

转载 作者:行者123 更新时间:2023-11-30 21:54:38 25 4
gpt4 key购买 nike

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-calculating block 移动到正确的位置后,它开始工作:

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);

关于c# - 无法打印出平均数组的结果,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/32914027/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com