如何从 JavaScript 函数返回中删除小数

问题描述 投票:0回答:1

我希望有人能指导我也许这无法完成?我有一个函数,我正在尝试删除小数(我想要返回整数)

function studentsPerAdmin(students, teachers, helpers) {
  const average = students / (teachers + helpers);
  if (average > 10) {
    console.log(`There are on average ${average} students for each educator.`);
  } else {
    console.log('Unfortunately this class will be cancelled due to not having enough students enrolled.');
  }
  return average
}


studentsPerAdmin(41, 1, 2)

我已经尝试使用数学函数,例如

math.round()
,但我仍在学习,我认为我没有正确使用它。目前的结果是

There are on average 13.666666666666666 students for each educator.
javascript function math
1个回答
-1
投票

要从函数返回整数,您可以使用 Math.floor()、Math.ceil() 或 Math.round() 相应地调整平均值。以下是修改函数的方法:

function studentsPerAdmin(students, teachers, helpers) {
    const average = students / (teachers + helpers);
    const wholeAverage = Math.floor(average); // Use Math.floor() to round down

    if (average > 10) {
        console.log(`There are on average ${wholeAverage} students for each educator.`);
    } else {
        console.log('Unfortunately this class will be cancelled due to not having enough students enrolled.');
    }

    return wholeAverage; // Return the whole number
}

studentsPerAdmin(41, 1, 2);

希望这有帮助。

最新问题
© www.soinside.com 2019 - 2025. All rights reserved.