Javascript如何从函数返回值中删除小数

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

嘿,JavaScript 新手,我希望有人可以指导我,也许这无法完成?我有一个函数,我正在尝试删除小数(我想要一个整数返回)感谢您提供的任何帮助或建议

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(),但我仍在学习,我认为我没有正确使用它 - 到目前为止,结果是

每位教育者平均有 13.666666666666666 名学生。

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 - 2024. All rights reserved.