// Meta:
// Using jQuery:
var per_row = $('meta[name="pageRows"]').prop('content');
// Vanilla JS:
var per_row = document.getElementsByName("pageRows").getAttribute('content');
// Element:
// Using jQuery:
var per_row = $('body').prop('pageRows');
// Vanilla JS:
var per_row = document.getElementsByTagName("body").getAttribute('pageRows');
// Don't forget to specify a default, in case the `META` tag doesn't exist.
我正在尝试接收每月的降雨量并将其平均。我无法打印出平均值的结果。我对数组和循环比较新,我不太确定我在哪里出错了。
我目前没有任何输出。一旦输入每个月的输入,程序就会关闭。
答案 0 :(得分:1)
你非常接近:在读数循环之后,不是在里面加上降雨量和除以月数的代码。
目前你不打印任何东西,因为纠正负面输入的循环包含打印平均值的代码。
您可以随时添加计算sum
。以下是您可以做的事情的概述:
for
循环答案 1 :(得分:1)
编辑:请考虑我对以下代码的修改。更新的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
答案 2 :(得分:1)
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);