简体   繁体   English

使用嵌套循环调用每次迭代(Javascript、node js、readlinesync)

[英]Calling each iteration with a nested loop (Javascript, node js, readlinesync)

Trying to solve this problem but I do not know how to display each iteration (each of the twelve months) with console.log.试图解决这个问题,但我不知道如何使用 console.log 显示每次迭代(十二个月的每一个月)。

The problem is: Write a program that uses nested loops to collect data and calculate the average rainfall over a period of years.问题是:编写一个程序,使用嵌套循环来收集数据并计算一段时间内的平均降雨量。 The program should first ask for the number of years.该程序应首先询问年数。 The outer loop will iterate once for each year.外循环将每年迭代一次。 The inner loop will iterate twelve times, once for each month.内部循环将迭代 12 次,每个月一次。 Each iteration of the inner loop will ask the user for the inches of rainfall for that month.内循环的每次迭代都会询问用户当月的降雨量英寸。 After all iterations, the program should display the number of months, the total inches of rainfall, and the average rainfall per month for the entire period.在所有迭代之后,程序应该显示月数、总降雨量英寸以及整个时期每月的平均降雨量。

This is what I have so far:这是我到目前为止:

var readlineSync = require('readline-sync');
var years = readlineSync.questionInt('Enter the number of years: ');

for (i = 0; i < years; i++) {
  for (j = 0; j < 11; j++) {
    var monthlyrainfall = readlineSync.questionInt('How many inches of rainfall was there this month? ');
  }
}

The missing point was how to calculate a sum of values inside a loop.缺少的一点是如何计算循环内的值的总和。 Take a look at this code, the vars totalInchesOfRain and averageRainfallPerMonth will calculate the values.看看这段代码,变量totalInchesOfRainaverageRainfallPerMonth将计算这些值。

var readlineSync= require('readline-sync');

var years = readlineSync.questionInt('Enter the number of years: ');

var totalInchesOfRain = 0;
for (i=0; i < years ; i++) {
    for(j=0; j<11; j++){
        var monthlyRainFall = readlineSync.questionInt('How many inches of rainfall was there this month? ');

        totalInchesOfRain += monthlyRainFall;
    }
}

var averageRainfallPerMonth = totalInchesOfRain / (years * 12);

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

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