Calculating a new population - c++

In a population, the birth rate is the percentage increase of the population due to births, and the death rate is the percentage decrease of the population due to deaths. Write a program that asks for the following:
The starting size of a population (minimum 2) (Prompt Enter starting size:)
The annual birth rate (Prompt Enter annual birth rate:)
The annual death rate (Prompt Enter annual death rate:)
The number of years to display (minimum 1) (Prompt Enter years to display:)
The program should then display the starting population and the projected population at the end of each year. It should use a function that calculates and returns the projected new size of the population after a year. The formula is
N = P(1 + B)(1 - D)
where N is the new population size, P is the previous population size, B is the birth rate, and D is the death rate. Annual birth rate and death rate are the typical numbers of births and deaths in a year per 1000 people, expressed as a decimal.
So, for example, if there are normally about 32 births and 26 deaths per 1000 people in a given population, the birth rate would be .032 and the death rate would be .026.
Here is my code; I am having trouble figuring out how to do the calculation.
#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

You can do this recursively or using a simple for loop.
E.g. Say if the numYears = 10, you would want to loop 10 times.
Create a temporary variable before your for loop and assign it the value of your startPop, e.g. endPop.
Then, starting with an initial population size of endPop, and death rate of deathRate as well as birth rate of birthRate, you calculate the population size after one year.
Having computed the population after one year in the first loop, you update endPop with the new value.
Subsequently, in the second loop, you use endPop once again as the new starting population size and the cycle repeats itself up till the end of your for loop, i.e. when 10 years have passed.
You did not declare the variable population in the above code snippet before using it.
Implementation:
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;
}
}
Take note that there is chance of over- and under-flow if your number gets too small or too big.
Implementation:
double projectedNewSize(double populationStartingSize, float annualBirthRate, float annualDeathRate) {
return populationStartingSize * (1 + annualBirthRate) * (1 - annualDeathRate);
}
For reading of numYears, you could consider using a do-while loop, :p.

Related

Why this formula could not be calculated in c++? [duplicate]

This question already has an answer here:
Dividing two integers to produce a float result [duplicate]
(1 answer)
Closed 1 year ago.
Here i want to calculate the number of sweets that i have been sold in Day 2.
int main()
{
float rate;
int left, total, sell ;
cout << "rate" ; // the rate that sweets have been sold per day
cin >> rate;
cout << "sell"; // number of sweets that have been sold in day1.
cin >> sell;
cout << "total"; // total number that the shops originally have
cin >> total;
left = total - sell;
sell = sell*(1+rate*(left/total));
cout << sell;
return 0;
}
And i want to calculate the numbers of sweets that have been sold in day2.
Assume the input are rate = 0.5, sell=100, total = 10000.
The output should be 14950. [ 10000 * (1+0.5*((10000-100)/10000)) ]
But why I still get 10000 after running the program.
Updated:
However, I have one more question. If i want to output a rounded up sell value. How could I do it? because i am not allowed to change the datatype of the variables, which means it should be still int sell; at the initialization part. I have tried cout << round((double) sell); But it still does not work.
As mentioned in the comment, you are doing an integer division. Here is the corrected code:-
#include<iostream>
using namespace std;
int main()
{
float rate;
int left, total, sell ;
cout << "rate" ; // the rate that sweets have been sold per day
cin >> rate;
cout << "sell"; // number of sweets that have been sold in day1.
cin >> sell;
cout << "total"; // total number that the shops originally have
cin >> total;
left = total - sell;
sell = sell*(1+rate*(left/(float)total));
cout << sell;
return 0;
}
I have typecasted the denominator.

C++ need help fixing to get desired output

I am working on a programming challenge from "Starting Out With C++: Early Objects, 10th Edition". I have the code about halfway done, but the output isn't coming out how it is supposed to be, and I am wondering how to fix it. I have it attached here and the desired output.
#include <iostream>
using namespace std;
int main()
{
float starting_num_of_organisms,
average_daily_population_increase,
size_of_daily_population;
int num_of_days_to_multiply;
cout << "Enter Starting Population: ";
while (!(cin >> starting_num_of_organisms) || starting_num_of_organisms < 2) {
cout << "Invalid. Population must be 2 or greater.";
cout << "Enter starting population: ";
cin.clear();
cin.ignore(123, '\n');
}
cout << "Enter positive daily growth % (.1 must be entered as 10): ";
while (!(cin >> average_daily_population_increase) || average_daily_population_increase < 0) {
cout << "Invalid. Daily Population Growth \n"
<< " must be greater than 0. \n"
<< "Enter Daily Population Growth (%): ";
cin.clear();
cin.ignore(123, '\n');
}
average_daily_population_increase *= .01;
cout << "Enter number of days to calculate: ";
while (!(cin >> num_of_days_to_multiply) || num_of_days_to_multiply < 1) {
cout << "Invalid. Number of days must not be less\n"
<< "than 1. Enter number of days to calculate: ";
cin.clear();
cin.ignore(123, '\n');
}
for (int i = 0; i < num_of_days_to_multiply; i++) {
cout << "Population size for day " << (i + 1);
cout << ": " << starting_num_of_organisms
<< endl;
starting_num_of_organisms += (starting_num_of_organisms * average_daily_population_increase);
}
return 0;
}
Here is the current output:
Enter Starting Population: 896.896
Enter positive daily growth % (.1 must be entered as 10): 2.785
Enter number of days to calculate: 8
Population size for day 1: 896.896
Population size for day 2: 921.875
Population size for day 3: 947.549
Population size for day 4: 973.938
Population size for day 5: 1001.06
Population size for day 6: 1028.94
Population size for day 7: 1057.6
Population size for day 8: 1087.05
The desired output is something like this below. The numbers are just for reference, and do not have to be specific to those numbers.
Enter starting population (greater than 2): 896.896
Enter positive daily growth % (.1 must be entered as 10): 2.785
Enter number of days to calculate (greater than 1): 8
----------------------------------
Start Population: 896.90
Daily Percent Growth: 2.79%
Number of Days: 8
Day Start End
Popl. Popl.
----------------------------
1 896.90 921.87
2 921.87 947.55
3 947.55 973.94
4 973.94 1001.06
5 1001.06 1028.94
6 1028.94 1057.60
7 1057.60 1087.05
8 1087.05 1117.33
It appears as though your code does the correct calculations. Just format the output and it will look like the desired output.
printf("%-10s%10s%10s\n", "day", "start", "end");
for(int i = 0; i < 30; i++)
printf("=");
printf("\n");
for (int i = 0; i < num_of_days_to_multiply; i++)
{
printf("%-10u%10.2lf", i + 1, starting_num_of_organisms);
starting_num_of_organisms +=
(starting_num_of_organisms *
average_daily_population_increase);
printf("%10.2lf\n", starting_num_of_organisms);
}
Note I used printf from the C libs (<stdio.h>), but the same can be achieved with cout, just much more verbose.
Output:
Enter Starting Population: 896.896
Enter positive daily growth % (.1 must be entered as 10): 2.785
Enter number of days to calculate: 8
day start end
==============================
1 896.90 921.87
2 921.87 947.55
3 947.55 973.94
4 973.94 1001.06
5 1001.06 1028.94
6 1028.94 1057.60
7 1057.60 1087.05
8 1087.05 1117.33

How could I properly set up this loan equation based on my code?

The question wants me to create 2 scenarios
The user accepts the dealer’s rebate offer and finances the car through his or her local credit union.
and
The user declines the dealer’s rebate offer but accepts the dealer’s lower financing rate.
It expects for me to use the periodic payment formula, which is: principal * rate / (1 – (rate + 1)-term) and use it to get either a monthly or annual payment.
The problem that I am having with my code I believe has something to do with my equations I am using to get annual or monthly loan payments, it for sure is not giving me the correct answer to my inputs and I do not know why.
I have tried changing the equations around several times and still no avail.
int main()
// these are the variables I will be using in maths for this project
double annualpayment; // what will be displayed once all is calculated annually
double monthlypayment; // what will be displayed once all is calculated monthly
double prinicple; // amount borrowed
double rate; // interest rate
double mterm; // what the user will enter for monthly term
double yterm; // what user will enter for yearly term
double years; // term of loan (yearly)
double month; // term of loan (monthly)
double sqrdMonth; // sqrt of term of loan (monthly)
double sqrdYear; // sqrt of term of loan (yearly)
char choice;
}
{
cout << "Enter your principle: " << endl; // total amount borrowing
cin >> prinicple;
cout << "Enter your your interest rate: " << endl; // interest rate on loan
cin >> rate;
cout << "Will this be (M)onthly or (Y)early payment? (enter y or m)"; // declaring if it will be a monthly or yearly payment
cin >> choice;
if (choice = 'M') // if its monthly
mterm = 12; // there are 12 months within a year
cout << "How many years will this loan be for?" << endl;
cin >> years; // I need this information for getting the exact
month = mterm * years;
sqrdMonth = sqrt(month); // I need to square root the months for the periodic payment formula
monthlypayment = (prinicple * rate) / (rate); sqrdMonth; // this is where my problem is
// ^^^^ why is it asking me to close my equation with a ';'
cout << "Your monthly loan payment is: ";
cout << monthlypayment;
if (choice = 'Y')
yterm = 1;
cout << "How many years will this loan be for?" << endl;
cin >> years;
years = yterm * years;
sqrdYear = sqrt(years); // I need to square root the years for the periodic payment formula
annualpayment = (prinicple * rate) / (rate); sqrdYear; // this is where my problem is
// ^^^^ why is it asking me to close my equation with a ';'
cout << "Your annual loan payment is: ";
cout << annualpayment;
}
}
I expect for the user to input the principle, rate, and length of loan then the compiler to do the math and then output the correct numbers. My actual results are negative numbers or irrational numbers.
Several mistakes
if (choice = 'M') // if its monthly
mterm = 12; // there are 12 months within a year
First point is that should say
if (choice == 'M') // if its monthly
mterm = 12; // there are 12 months within a year
In C++ we use == to test for equality and = to assign to a variable.
Even more seriously think about this
if (choice == 'M') // if its monthly
mterm = 12; // there are 12 months within a year
cout << "How many years will this loan be for?" << endl;
cin >> years; // I need this information for getting the exact
month = mterm * years;
Now suppose choice is not 'M' what do you think the value of mterm will be?
The answer is that it is undefined. Yet you are using the variable in the formula two lines down. It's bad to use variables with undefined values.
It looks to me that you need to restructure your code to include more statements inside of the if statement
if (choice == 'M')
{
mterm = 12; // there are 12 months within a year
cout << "How many years will this loan be for?" << endl;
cin >> years; // I need this information for getting the exact
month = mterm * years;
sqrdMonth = sqrt(month); // I need to square root the months for the periodic payment formula
monthlypayment = (prinicple * rate) / (rate); sqrdMonth; // this is where my problem is
// ^^^^ why is it asking me to close my equation with a ';'
cout << "Your monthly loan payment is: ";
cout << monthlypayment;
}
Finally this
monthlypayment = (prinicple * rate) / (rate); sqrdMonth;
I've no idea why you've got two semi-colons. Makes no sense to me, but I not sure what the formula should be. There's no mention of square roots in the formula in your question, so I'm not sure why you included one here.

C++ Adding sum of multiple function calls within a loop

I've been working on an assignment that calculates the total profit/loss for multiple stock sales via a looping function with information inputted by user for each stock sale. I did a thorough amount of googling to no avail. I was able to get the function working within the loop but I have not been able to figure out how to add the profit/loss from multiple sales - instead only displaying profit/loss for each individual function call. My function's algorithm checks out if you manually add the totals for each sale, just unclear on how to find the sum of multiple function calls.
Here is the sample data I'm suppose to enter that should display the total profit of $3324.00:
sale numberOfShares salePrice salesCommission purchasePrice purchaseCommission
1 25 15 7.50 5 2.50
2 100 2.50 12 1.75 8
3 1000 5.10 51 2 20
And my code thus far:
#include <iostream>
#include <iomanip>
using namespace std;
// Function prototype
double stockProfitFunction(double NS, double PP, double PC, double SP, double SC);
// Main Function
int main()
{
// Format output
cout << fixed << setprecision(2);
// Initialize variables
double profit,
numberOfShares,
salePrice,
saleCommission,
purchasePrice,
purchaseComission;
int numberOfSales;
// Get # of sales from user
cout << "Multiple Stock Profit Calculator\n--------------------------------\n\n";
cout << "How many sales do you wish to enter?: ";
cin >> numberOfSales;
cout << endl;
// Perform function in loop for number of sales
for (int i = 1; i <= numberOfSales; i++)
{
system("cls"); // Clears screen
cout << "Multiple Stock Profit Calculator\n";
cout << "(Currently entering stock sale #" << i << ")\n----------------------------------\n";
// Get information from user
cout << "Enter number of shares: ";
cin >> numberOfShares;
cout << "Enter sale price: ";
cin >> salePrice;
cout << "Enter sales commission: ";
cin >> saleCommission;
cout << "Enter purchase price: ";
cin >> purchasePrice;
cout << "Enter purchase commission: ";
cin >> purchaseComission;
//Calcualtes profit with function
profit = stockProfitFunction(numberOfShares, purchasePrice, purchaseComission, salePrice, saleCommission);
// Display "profit" or "loss" depending on positive or negative value returned by function
if (profit >= 0)
{
cout << "\n-----------------------\n";
cout << "You earned a profit of: $" << profit << endl;
cout << "(Press enter to input next sale)";
cin.get();
cin.get();
}
else
{
cout << "\n-----------------------\n";
cout << "You had a loss of: $" << profit << endl;
cout << "(Press enter to input next sale)";
cin.get();
cin.get();
}
}
return 0;
}
// Stock Profit Function, returns profit
double stockProfitFunction(double NS, double PP, double PC, double SP, double SC)
{
return ((NS * SP) - SC) - ((NS * PP) + PC);
}
Thanks for taking a look!
Initialize a variable to zero.
Each time you calculate a profit, add it to that variable.
Where desired, output the value of that variable.
By the way:
system("cls"); // Clears screen
That's a very bad habit to get into. Maybe on your machine, cls clears the screen, but you have no way to know what the cls command might do on someone else's machine. (On mine, there is no command called cls, the clear screen command is clear.) Unless you absolutely have no choice, you should strongly avoid using system in your C++ code.

C++ Input validation to make sure a number was entered instead of a letter

So I'm trying to set this program up to calculate the balance of an account. I need to make sure the starting balance is entered as a positive number. I have the positive part down, but how do I make sure that the input is also a number and not letters or other non-numbers?
#include <iostream>
#include <cmath>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
double startBal, // Starting balance of the savings account
ratePercent, // Annual percentage interest rate on account
rateAnnual, // Annual decimal interest rate on account
rateMonth, // Monthly decimal interest rate on account
deposit1, // First month's deposits
deposit2, // Second month's deposits
deposit3, // Third month's deposits
interest1, // Interest earned after first month
interest2, // Interest earned after second month
interest3, // Interest earned after third month
count; // Count the iterations
// Get the starting balance for the account.
cout << "What is the starting balance of the account?" << endl;
cin >> startBal;
while (startBal < 0 ) {
cout << "Input must be a positive number. Please enter a valid number." << endl;
cin >> startBal;
}
// Get the annual percentage rate.
cout << "What is the annual interest rate in percentage form?" << endl;
cin >> ratePercent;
// Calculate the annual decimal rate for the account.
rateAnnual = ratePercent / 100;
// Calculate the monthly decimal rate for the account.
rateMonth = rateAnnual / 12;
while (count = 1; count <= 3; count++)
{
}
return 0;
}
Thanks!!!
You can verify if cin was successful:
double startBal;
while (!(std::cin >> startBal)) {
std::cin.clear();
std::cin.ignore(std::numeric_limits<streamsize>::max(), '\n');
std::cout << "Enter a valid number\n";
}
std::cout << startBal << endl;
Don't forget to #include <limits> to use std::numeric_limits<streamsize>::max().
double x;
std::cout << "Enter a number: ";
std::cin >> x;
while(std::cin.fail())
{
std::cin.clear();
std::cin.ignore(numeric_limits<streamsize>::max(),'\n');
std::cout << "Bad entry. Enter a NUMBER: ";
std::cin >> x;
}
Replace x and double with whatever variable name and type you need. And obviously, modify your prompts to whatever is necessary.
What you're asking for is actually quite difficult. The only completely correct way is to read your input as a string, then see if the string is in the right format for a number, and only then convert the string to a number. I think that's quite difficult when you're just a beginner.