在一个小镇,人口是p0 = 1000在年初。人口每年定期增加2 percent,而且50每年都会有新的居民来到该镇居住。该镇需要多少年才能看到其人口大于或等于p = 1200居民?
function nbYear(p0, percent, aug, p) {
// your code
}
nbYear(1500, 5, 100, 5000), 15)
<script>
function nbYear(p0, percent, aug, p) {
var year = 0;
while (p0 < p) {
p0 = Math.floor(p0 + p0 * percent / 100) + aug;
console.log(p0)
year++;
}
return year;
}
console.log(`需要${nbYear(1000, 2, 50, 1200)}年`)
console.log(`需要${nbYear(1500, 5, 100, 5000)}年`)
</script>
function nbYear(p0, percent, aug, p) {
var num = 0;
// your code
if(p0 < p){
p0 = p0 + p0 * percent * 0.01 + aug;
num++;
num += nbYear(p0, percent, aug, p)
}
return num;
}
第一年结束时,将有:
1000+10000.02+50=>1070居民
第二年结束时,将有:
1070+10700.02+50=>1141名居民(居民人数为整数)
第三年结束时,将有:
1141 + 1141 * 0.02 + 50 => 1213
将百分比参数转换为函数主体中的百分比: