fork download
  1. //Matthew Santos CS1A Ch. 6, Pg. 373, #15
  2. /***********************************************
  3.  *
  4.  * CALCULATE POPULATION
  5.  * _____________________________________________
  6.  * Calculates and displays the population size
  7.  * over any number of years based off the
  8.  * starting size and annual birth and death rate.
  9.  * _____________________________________________
  10.  * INPUT
  11.  * startingPop : starting population
  12.  * birthRate : birth rate as a decimal
  13.  * deathRate : death rate as a decimal
  14.  * years : years simulated
  15.  *
  16.  * OUTPUT
  17.  * population for the given years
  18.  ***********************************************/
  19. #include <iostream>
  20. #include <iomanip>
  21. using namespace std;
  22.  
  23. double calculatePopulation(double, double, double);
  24.  
  25. int main() {
  26. double startingPop;
  27. double birthRate;
  28. double deathRate;
  29. int years;
  30.  
  31. // Input for starting population
  32. cout << "Enter the starting size of the population: ";
  33. cin >> startingPop;
  34. while (startingPop < 2)
  35. {
  36. cout << "Starting size must be at least 2. Enter again: ";
  37. cin >> startingPop;
  38. }
  39.  
  40. // Input for birth rate
  41. cout << "Enter the annual birth rate (as a decimal, example 0.05 for 5%): ";
  42. cin >> birthRate;
  43. while (birthRate < 0)
  44. {
  45. cout << "Birth rate cannot be negative. Enter again: ";
  46. cin >> birthRate;
  47. }
  48.  
  49. // Input for death rate
  50. cout << "Enter the annual death rate (as a decimal, example 0.02 for 2%): ";
  51. cin >> deathRate;
  52. while (deathRate < 0)
  53. {
  54. cout << "Death rate cannot be negative. Enter again: ";
  55. cin >> deathRate;
  56. }
  57.  
  58. // Input for number of years
  59. cout << "Enter the number of years to display: ";
  60. cin >> years;
  61. while (years < 1)
  62. {
  63. cout << "Number of years must be at least 1. Enter again: ";
  64. cin >> years;
  65. }
  66.  
  67. // Display the population each year
  68. cout << fixed << setprecision(0);
  69. cout << "\nYear\tPopulation\n";
  70. cout << "-----------------\n";
  71.  
  72. double population = startingPop;
  73. for (int year = 1; year <= years; ++year)
  74. {
  75. population = calculatePopulation(population, birthRate, deathRate);
  76. cout << year << "\t" << population << endl;
  77. }
  78.  
  79. return 0;
  80. }
  81.  
  82. double calculatePopulation(double P, double B, double D)
  83. {
  84. return P + (B * P) - (D * P);
  85. }
Success #stdin #stdout 0.01s 5320KB
stdin
500 0.07 0.02 10
stdout
Enter the starting size of the population: Enter the annual birth rate (as a decimal, example 0.05 for 5%): Enter the annual death rate (as a decimal, example 0.02 for 2%): Enter the number of years to display: 
Year	Population
-----------------
1	525
2	551
3	579
4	608
5	638
6	670
7	704
8	739
9	776
10	814