'C++ program to calculate the population
I'm trying to make a program that calculates the population after any number of years using the starting size of the population, the number of years, and the death and birth rate per year. The issue is that I can't figure out why the result always shows me the starting size of the population (that the user enters).
The role of the equation in the alcopop function and the for loop in the main:
The equation adds the number of births and deaths of the current year to the current population and stores them in N. The starting population is then set equal to N for the next year (the next iteration of the for loop) so that it calculates the percentage of death and birth.
The equation is not subject to change!!
#include<iostream>
using namespace std;
int N;
void calcpop(int P, int D, int B);
int main() {
int birth, death, population,years ;
cout << "Enter the number of years: ";
cin >> years;
while (years < 1) {
cout << "You can't use a number smaller than 1.\n";
cout << "Enter the number of years : ";
cin >> years;
}
cout<< "Enter the starting size of the population : ";
cin >> population;
while (population < 2) {
cout << "You can't use a number smaller than 2.\n";
cout << "Enter the starting size of the population : ";
cin >> population;
}
cout << "Enter the annual birth rate : ";
cin >> birth;
while (birth < 0) {
cout << "You cant use a negative number.\n";
cout << "Enter the annual birth rate : ";
cin >> birth;
}
cout << "Enter the annual death rate : ";
cin >> death;
while (death < 0) {
cout << "You cant use a negative number.\n";
cout << "Enter the annual death rate : ";
cin >> death;
}
death *= .01; //death rate %
birth *= .01; // birth rate %
for (int count = 0; count < years; count++) {
calcpop(population, death, birth);
population = N;
}
cout << "The size of the population after " << years << " years is : " << N;
return 0;
}
void calcpop(int P, int D, int B) {
N = P + (P * B) - (P * D); //calculates the population for 1 year
//N is the new population (population of the next year
//P is the population of the current year (previously N)
//D id death rate %
//B is birth rate %
}
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|
