在人口中,出生率是出生人口增加的百分比,死亡率是死亡人口减少的百分比。编写一个要求以下内容的程序:
然后,该计划应显示每年年底的起始人口和预计人口。它应该使用一个函数来计算并返回一年后人口的预计新大小。公式是
N = P(1 + B)(1 - D)
其中N
是新的人口规模,P
是之前的人口规模,B
是出生率,D
是死亡率。年出生率和死亡率是每1000人一年中的典型出生和死亡人数,以小数表示。
因此,例如,如果特定人群中每1000人通常有大约32个分娩和26个死亡,则出生率为.032,死亡率为.026。
这是我的代码;我无法弄清楚如何进行计算。
#include "stdafx.h" // Defines IDE required "pre-compiled" definition files
#include <iomanip>
#include <iostream>
using namespace std
int main ()
{
double startPop, // To hold the starting population.
float birthRate, // To hold the birth rate.
float deathRate; // To hold the death rate.
int numYears; // To hold the number of years to track population changes.
// Input and validate starting population
cout << "This program calculates population change.\n";
cout << "Enter the starting population size: ";
cin >> startPop;
while (startPop < 2.0)
{
cout << "Starting population must be 2 or more. Please re-enter: ";
cin >> startPop;
}
// Input and validate annual birth and death rates
cout << "Enter the annual birth rate (as % of current population): ";
cin >> birthRate;
while (birthRate < 0)
{
cout << "Birth rate percent cannot be negative. Please re-enter: ";
cin >> birthRate;
}
birthRate = birthRate / 100; // Convert from % to decimal.
cout << "Enter the annual death rate (as % of current population): ";
cin >> deathRate;
while (deathRate < 0)
{
cout << "Death rate percent cannot be negative. Please re-enter: ";
cin >> deathRate;
}
deathRate = deathRate / 100; // Convert from % to decimal.
cout << "For how many years do you wish to view population changes? ";
cin >> numYears;
while (numYears < 1)
{
cout << "Years must be one or more. Please re-enter: ";
cin >> numYears;
population = projectedNewSize(populationStartingSize, annualBirthRate, annualDeathRate);
cout << population << endl;
populationStartingSize = population;
}
printPopulations(startPop, birthRate, deathRate, numYears);
return 0;
} // End of main function
答案 0 :(得分:1)
您可以递归执行此操作或使用简单的for
循环。
E.g。假设如果numYears = 10,则需要循环10次。
在for
循环之前创建一个临时变量,并为其指定startPop
的值,例如endPop
。
然后,从最初的人口规模endPop
,deathRate
的死亡率以及birthRate
的出生率开始,您计算一年后的人口规模。
在第一个循环中计算一年后的人口时,您使用新值更新endPop
。
随后,在第二个循环中,再次使用endPop
作为新的起始种群大小,循环重复直到for
循环结束,即10年过去。
在使用之前,您没有在上面的代码段中声明变量population
。
<强>实施强>
while (numYears < 1)
{
cout << "Years must be one or more. Please re-enter: ";
cin >> numYears;
}
double population = populationStartingSize;
for ( int i = 0; i < numYears; i++) {
population = projectedNewSize(population, annualBirthRate, annualDeathRate);
cout << "After " << i+1 << "years: " << population << endl;
}
}
请注意,如果您的号码太小或太大,就有可能出现过度流量和流量不足。
<强>实施强>
double projectedNewSize(double populationStartingSize, float annualBirthRate, float annualDeathRate) {
return populationStartingSize * (1 + annualBirthRate) * (1 - annualDeathRate);
}
要阅读numYears
,您可以考虑使用do-while
循环:p。