简体   繁体   English

使用循环查找数组中的最低/最高数字

[英]Finding the lowest/highest number in an array using a loop

For my web development class, I have the following assignment: 对于我的Web开发课程,我有以下作业:

Before your boss allows adjustable thermostats in the office suite, he must be convinced that major temperature variations occur in different officers and within each office on different days. 在您的老板允许在办公室套件中使用可调恒温器之前,必须使他确信,不同办公室的人员和办公室在不同的日期会出现较大的温度变化。 You're to write a program that allows each employee to enter the temperature at noon on each of five days and displays the highest, lowest, and average (mean) temperatures. 您要编写一个程序,该程序允许每个员工在五天的中午输入温度,并显示最高,最低和平均(平均)温度。 Use a For loop to take the five readings. 使用For循环获取五个读数。 ( Hint : Initialize the highest and lowest temperature variable to the first temperature that's read, and then compare other temperatures to see whether they're lower or higher.) Use the parseFloat() method to convert your temperature input to a decimal number and display the average to one decimal place. 提示 :将最高和最低温度变量初始化为所读取的第一个温度,然后比较其他温度以查看它们是较低还是较高。)使用parseFloat()方法将温度输入转换为十进制数字并显示平均到小数点后一位。

How can I find the average temperature? 如何找到平均温度?

<!DOCTYPE HTML>
<html>
<body>
    <script type="text/javascript">
    var high; // highest temperature
    var low; // lowest temperature
    var avg; // average temperature

    var temperatures = [];

    for (var i = 0; i < 5; i++) {
        high = temperatures[0];
        low = temperatures[0];

        temperatures.push(parseFloat(prompt("Enter the temperature for day " + (i+1))));

        if (high < temperatures[i]) {
            high = temperatures[i]; }
        if (low > temperatures[i]) {
            low = temperatures[i]; }

    }

    document.write("The highest temperature is " + high + ".<br>");
    document.write("The lowest temperature was " + low + ".<br>");
    document.write("The average temperature was " + avg + ".");
    </script>
</body>
</html>

You are setting values in alltemp to the high or the low, not the other way around. 您正在将值临时设置为较高或较低,而不是相反。 Here's a fiddle that shows you how you can do this (since you have to use a for loop, but there are cleaner ways): https://jsfiddle.net/vtbahu3v/ 这是一个小提琴,向您展示如何执行此操作(因为必须使用for循环,但是有更清洁的方法): https : //jsfiddle.net/vtbahu3v/

var nums = [2, 55, 3, 87, 4, 23],
    high = low = nums[0];

for(var i = 0; i < nums.length; i++) {
    high = Math.max(high, nums[i]);
  low = Math.min(low, nums[i]);
}

alert("High is " + high);
alert("Low is " + low);

Step 1 第1步

@Emily, here's something to get you started with using a for loop to collect the user input. @Emily,这是使您开始使用for循环收集用户输入的内容。

var temperatures = [];

for (var i = 1; i <= 5; i++) {
    var temperature = prompt('Enter temperature for day ' + i);
    // Parse input and add it to the temperatures array
}

Step 2 第2步

Awesome, so you now have an array of 5 temperatures called temperatures . 太棒了,所以您现在有5个温度数组,称为temperatures In the example below, I've split the line for capturing and pushing the value into two separate statements for readability. 在下面的示例中,为了便于阅读,我将捕获和推送值的行分为两个单独的语句。 As follows: 如下:

var temperature = prompt('Enter the temperature for day ' + (i + 1));
temperatures.push(parseFloat(temperature));

Another minor change that you need to make is that you're assigning high and low values inside the loop, but before any values have been pushed to the temperatures array, so we'll need to look at that. 您需要做的另一个小更改是,您要在循环内分配high值和low ,但是要在将任何值推入temperatures数组之前,所以我们需要研究一下。

But first, finding the average temperature. 但是首先要找到平均温度。 So average, as you already know, is the sum of all values, divided by the number of values. 众所周知,平均值就是所有值的总和除以值的数量。 On each iteration of our loop, we're getting the next temperature value. 在循环的每次迭代中,我们都获得下一个温度值。 So we could use the loop to add all of those values together. 因此,我们可以使用循环将所有这些值加在一起。 As follows: 如下:

var temperatures = [];
var total = 0;
var high;
var low;
var avg;

for (var i = 0; i < 5; i++) {
    // Capture, parse and append temperature to temperatures array
    var temperature = prompt('Enter the temperature for day ' + (i + 1));
    temperatures.push(parseFloat(temperature));

    // Increment total by new temperature value
    total += temperature;
}

But what about the high and low temperatures? 但是highlow怎么办? If we take the code from your latest question update, on every iteration of the loop, high and low will be reset to the first temperature, and then you'll compare it to the current temperature in the loop. 如果我们从最新问题更新中获取代码,则在循环的每次迭代中, highlow将重置为第一个温度,然后将其与循环中的当前温度进行比较。 This won't work. 这行不通。

What we could do however, is to set high and low to very low and very high values, so that any temperature entered by the user would always be higher or lower. 但是,我们可以做的是将highlow设置为非常低和非常高的值,以便用户输入的任何温度始终会更高或更低。 For example: 例如:

var high = Number.NEGATIVE_INFINITY;
var low = Number.POSITIVE_INFINITY;

Then on each iteration of the loop, we take the code you've already written to compare the current temperature against the previous high and low values. 然后,在循环的每次迭代中,我们将使用您已经编写的代码将当前温度与之前的high值和low进行比较。 As follows: 如下:

var temperatures = [];
var total = 0;
var high = Number.NEGATIVE_INFINITY;
var low = Number.POSITIVE_INFINITY;
var avg;

for (var i = 0; i < 5; i++) {
    // Capture, parse and append temperature to temperatures array
    var temperature = prompt('Enter the temperature for day ' + (i + 1));
    temperatures.push(parseFloat(temperature));

    // Increment total by new temperature value
    total += temperature;

    // Compare high and low temperatures
    if (high < temperature) high = temperature;
    if (low > temperature) low = temperature;
}

And finally, how do you calculate the average? 最后,您如何计算平均值?

// Calculate average temperature
avg = total / temperatures.length;

Step 3 第三步

This code could be improved further, if you're interested. 如果您有兴趣,可以进一步改进此代码。 But it may be beyond the scope of this question. 但这可能超出了这个问题的范围。

If you would like to improve it, take a look at Math.min() , Math.max() , and apply() . 如果您想改善它,请看Math.min()Math.max()apply() I'm happy to post some more code to show how these can be used for getting the high and low temperatures, as well as Array.prototype.reduce for calculating the average. 我很高兴发布更多代码来展示如何将它们用于获得高温和低温,以及Array.prototype.reduce用于计算平均值。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM