计算温度和math.round的平均值?

时间:2018-01-06 14:09:26

标签: javascript arrays average

我试图在我的javascript类中解决一项任务。因此,任务是计算不同城市中某些不同温度的平均值。我们应该使用数组,我认为我完成了大部分工作,但现在我想用math.round来完成数字。但是我不知道我应该把math.round放在哪里,我想这是一个非常简单的问题,但我不能让它工作。我也想摆脱" NaN"你可以在右上方看到。感谢您的帮助!

我的代码如下:



"styles": [
      "styles.css",
      "../node_modules/font-awesome/css/font-awesome.css"
    ]

var temp = [
  ["City", "00-08", "08-16", "16-24", "Average"],
  ["New York", 12, 16, 9],
  ["London", 13, 15, 10],
  ["Stockholm", 13, 15, 13],
  ["Oslo", 14, 16, 15],
  ["Hong Kong", 13, 14, 12]
];

function printit() {
  var MyinnerHTML = "<table border='1'>";

  for (i = 0; i < temp.length; i++) //Loop vertical 
  {
    MyinnerHTML += "<tr>";
    for (j = 0; j < temp[i].length; j++) //Loop horisontal 
    {
      MyinnerHTML += "<td>" + temp[i][j] + "</td>";
    } {
      total = temp[i][1] + temp[i][2] + temp[i][3];

      temp[i].shift(); //So it doesn't calculate the average with the city name

      average = total / temp[i].length;

    }

    {
      MyinnerHTML += "<td>" + average + "</td>";
    }
    MyinnerHTML += "<tr/>";
  }
  MyinnerHTML += "</table>";

  document.getElementById("container").innerHTML = MyinnerHTML;
}
&#13;
&#13;
&#13;

希望它在完成后看起来像这样。

enter image description here

1 个答案:

答案 0 :(得分:0)

您可以通过首先将平均值乘以10,在其上应用Math.round,然后再将其除以10来获得舍入数字。以下是我建议创建HTML代码的方法:

const temp = [
  ["City", "00-08", "08-16", "16-24", "Average"],
  ["New York", 12, 16, 9],
  ["London", 13, 15, 10],
  ["Stockholm", 13, 15, 13],
  ["Oslo", 14, 16, 15],
  ["Hong Kong", 13, 14, 12]
];

const html = temp.map( (row, i) => {
    if (i) {
        const avg = row.slice(1).reduce( (a,b) => a+b ) / (row.length-1);
        row.push(Math.round(avg*10)/10);
    }
    return '<td>' + row.join('</td><td>') + '</td>';
}).join('</tr><tr>');

document.getElementById("container").innerHTML = 
    "<table border='1'><tr>" + html + "</tr></table>";  
<h3> Temperature in different cities (Assignment1) </h3>
<div id="container"></div>