在javascript中创建重复的数学函数?

在javascript中创建重复的数学函数?,javascript,math,Javascript,Math,这似乎是一个愚蠢的问题,但我大约一周前才开始学习javascript。我决定尝试用javascript自动化我的家庭作业,但我不知道如何做到这一点。其工作原理如下: 你在计算一个人口达到一定数量需要多少年 我们将把这个简单化,并计算增长率。人口将从50开始,我们希望达到100 到目前为止,这就是我所拥有的: function newPeople(start, growth) { var a = start * growth; var b = start + a;

这似乎是一个愚蠢的问题,但我大约一周前才开始学习javascript。我决定尝试用javascript自动化我的家庭作业,但我不知道如何做到这一点。其工作原理如下:

你在计算一个人口达到一定数量需要多少年

我们将把这个简单化,并计算增长率。人口将从50开始,我们希望达到100

到目前为止,这就是我所拥有的:

    function newPeople(start, growth) {
    var a = start * growth;
    var b = start + a;
    var c = Math.round(b);
    var d = c * growth;
    var e = c + d;
    var f = Math.round(e);
    return f;
    }

    newPeople(50, .20);
您可以看到,每次都可以通过创建一组新的变量手动完成,但如何实现自动化?

这应该可以:

// start is the current population
// growth is the growth rate
// target is the target population
function newPeople(start, growth, target) {

    var pop = start;
    var years = 0;
    while(pop <= target) {
        years++; // increment year by one
        pop = pop + Math.floor(pop * growth);
    }

    // return what you need from the function here
    // "return years;" will give you the number of years it takes to go from "start" to "target"
    // "return pop;" will give you the actual population after "years" number of years
}
//开始是当前人口
//增长就是增长率
//目标是目标人群
功能新人(起步、成长、目标){
var pop=启动;
var年数=0;
而(pop这应该有效:

// start is the current population
// growth is the growth rate
// target is the target population
function newPeople(start, growth, target) {

    var pop = start;
    var years = 0;
    while(pop <= target) {
        years++; // increment year by one
        pop = pop + Math.floor(pop * growth);
    }

    // return what you need from the function here
    // "return years;" will give you the number of years it takes to go from "start" to "target"
    // "return pop;" will give you the actual population after "years" number of years
}
//开始是当前人口
//增长就是增长率
//目标是目标人群
功能新人(起步、成长、目标){
var pop=启动;
var年数=0;
while(pop)使用a,并继续乘以相同的变量。使用a,并继续乘以相同的变量。