Is there a calculation error in my program? - c++

Apparently there is a calculation error somewhere in my program, but I simply can’t find it.
The only information I have as to why there is a calculation error is this following feedback given by MyProgrammingLab (A site that automatically tests code to see if it's incorrect or not). I don't know what values were entered for the annual death rate and annual birth rate to cause it. Could it be that I'm right but MyProgrammingLab is wrong? Honestly, all my own tests seem fine.
Expected Output:
Year 1: 200 176
Year 2: 176 154
Year 3: 154 135
Year 4: 135 118
Year 5: 118 103
Year 6: 103 90
Year 7: 90 79
Actual Output:
Year 1: 200 199
Year 2: 199 198
Year 3: 198 197
Year 4: 197 196
Year 5: 196 195
Year 6: 195 194
Year 7: 194 193
I built the program according to the following assignment:
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 number 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.
My code:
#include <iostream>
using namespace std;
int projectedNewSize(float population, float annualBirthRate, float annualDeathRate) {
float annualBirthRate2 = annualBirthRate / 1000;
float annualDeathRate2 = annualDeathRate / 1000;
int newpopulation = population * (1 + annualBirthRate2) * (1 - annualDeathRate2);
return newpopulation;
}
int main() {
int populationStartingSize = 0;
float annualBirthRate = 0;
float annualDeathRate = 0;
int numberOfYearsToDisplay = 0;
do {
cout << "Enter starting population size: ";
cin >> populationStartingSize;
cout << "Enter annual birth rate: ";
cin >> annualBirthRate;
cout << "Enter annual death rate: ";
cin >> annualDeathRate;
cout << "Enter years to display: ";
cin >> numberOfYearsToDisplay;
} while (!(populationStartingSize >= 2) || !(numberOfYearsToDisplay >= 1));
int population;
for (int i = 1; i <= numberOfYearsToDisplay; i++) {
cout << "Year " << i << ": " << populationStartingSize << " ";
population = projectedNewSize(populationStartingSize, annualBirthRate, annualDeathRate);
cout << population << endl;
populationStartingSize = population;
}
system("pause");
return 0;
}

So, The answer is
There is no need to divide the annualBirthRate and the annualDeathRate by 1000. Since annualBirthRate is calculated as annual births per 1000 of a population, It need not be divided by 1000 again.
Thus removing these lines
float annualBirthRate2 = annualBirthRate / 1000;
float annualDeathRate2 = annualDeathRate / 1000;
and changing
int newpopulation = population * (1 + annualBirthRate2) * (1 - annualDeathRate2);
to
int newpopulation = population * (1 + annualBirthRate) * (1 - annualDeathRate);
So, the final code would look like this:
#include <iostream>
using namespace std;
int projectedNewSize(float population, float annualBirthRate, float annualDeathRate) {
int newpopulation = population * (1 + annualBirthRate) * (1 - annualDeathRate);
return newpopulation;
}
int main() {
int populationStartingSize = 0;
float annualBirthRate = 0;
float annualDeathRate = 0;
int numberOfYearsToDisplay = 0;
do {
cout << "Enter starting population size: ";
cin >> populationStartingSize;
cout << "Enter annual birth rate: ";
cin >> annualBirthRate;
cout << "Enter annual death rate: ";
cin >> annualDeathRate;
cout << "Enter years to display: ";
cin >> numberOfYearsToDisplay;
} while (!(populationStartingSize >= 2) || !(numberOfYearsToDisplay >= 1));
int population;
for (int i = 1; i <= numberOfYearsToDisplay; i++) {
cout << "Year " << i << ": " << populationStartingSize << " ";
population = projectedNewSize(populationStartingSize, annualBirthRate, annualDeathRate);
cout << population << endl;
populationStartingSize = population;
}
system("pause");
return 0;
}
You guys discussed in the comments section and left the question unanswered..

int projectedNewSize(float population, float annualBirthRate, float annualDeathRate) {
int newpopulation = roundf(population * (1.0 + annualBirthRate) * (1.0 - annualDeathRate);
return newpopulation;
}
In the calculatiton you dont have to consider the factor of 1000 if it is already done in the input values. But if you want a 'most accurate' table you have to round the values in a proper mind. The return of the calculation is a float. If you assign it to an int - it always will be truncated. A little difference wich will be carried over from one loop to the next, ending up in some reasonable differences to the expected values at the end. The most proper way would be to change the type of 'newcalculation' to float and round only when display the value.

N = P + BP - DP
Program asked for birthrate and death rate, assume user entered 5 for 5%.
Basic math needs to be calculated here 5/100 = 0.05
The formula is now
N = P + (BP/100) - (DP/100)
Replace
float annualBirthRate2 = annualBirthRate / 1000;
float annualDeathRate2 = annualDeathRate / 1000;
int newpopulation = population * (1 + annualBirthRate2) * (1 - annualDeathRate2);
With
int newpopulation = population + (population * birthRate/100) - (population * deathRate/100)

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.

Get double as a result of division of integer values

If a person has low income (<= 25,000) and the consulting time is less than or equal to 30 minutes, there are no charges; otherwise, the service charges are 40% of the regular hourly rate for the time over 30 minutes.
For others, if the consulting time is less than or equal to 20 minutes, there are no service charges; otherwise, service charges are 70% of the regular hourly rate for the time over 20 minutes.
(For example, suppose that a person has low income and spent 1 hour and 15 minutes, and the hourly rate is $70.00. Then the billing amount is 70.00 * 0.40 * (45 / 60) = $21.00.)
Write a program in C++ that prompts the user to enter the hourly rate, the total consulting time, and whether the person has low income. The program should output the billing amount.
This is what I have done so far and the program looks correct to me, but for some reason I do not get the correct output. I get 0.00 which is a wrong output value.
#include<iostream>
#include <iomanip>
using namespace std;
double calculateBill(int income, int consultingMinutes, double hourlyRate);
int main()
{
int income;
double consultingMinutes;
double hourlyRate;
cout << "Please enter the clients income: $" ;
cin >> income;
cout << "Please enter the consulting time in minutes: ";
cin >> consultingMinutes;
cout << "Please enter the hourly rate: $";
cin >> hourlyRate; cout << fixed << showpoint << setprecision(2);
cout << "Your total bill ammount comes to: $" << calculateBill(income, consultingMinutes, hourlyRate) << endl;
return 0;
}
double calculateBill(int income, int consultingMinutes, double hourlyRate)
{
if (income <= 25000) {
if (consultingMinutes <= 30)
return 0;
else
return hourlyRate * 0.40 * ((consultingMinutes - 30) / 60);
}
else {
if (consultingMinutes <= 20)
return 0;
else
return hourlyRate * 0.70 * ((consultingMinutes - 20) / 60);
}
}
Mixing of integers and floats is not a very good thing. Try this:
return hourlyRate * 0.40 * (((double) consultingMinutes - 30.0) / 60.0);
instead of this:
return hourlyRate * 0.40 * ((consultingMinutes - 30) / 60);
(And apply the same fix for the second wrong place return hourlyRate * 0.70 * ((consultingMinutes - 20) / 60);)

Array not displaying proper output

I'm writing this program that calculates the amount of hours that employees work. If the employee ends up working more than 40 hours, than he'll get an additional time and half for every hour that passes 40. My issue is when it comes to the output. In the output, it shows the amount of sales tax, federal tax, gross income, and net; however if the employee puts in that he has worked less than 40 hours, everything displays properly; however, once the employee puts in that he has worked more than 40 hours for some reason it shows the taxes, and net, gross as 0.00.
For example, if less than 40, the following would display.
F-Name: L-Name: HorsWrked: HrlyRate: TimeHalf: S-Tax: F-Tax: Fica: Gross:
Employee Last 39.00 22.00 1.50 60.06 128.70 34.32 858.00
If more than 40, the following is being displayed.
F-Name: L-Name: HorsWrked: HrlyRate: TimeHalf: S-Tax: F-Tax: Fica: Gross:
Employee Last 45.00 22.00 1.50 0.00 0.00 0.00 0.00
Any tips, hints, advice is appreciated.``
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
//Set variables
int const size = 2;
double timeHalf = 0.0, hoursWorked[size], gross[size], net[size], hourlyRate[size], totalTax;
string firstName[size], lastName[size];
const double stateTax = 0.07, fedTax = 0.15, fica = 0.04;
double sTax = 0.0, fTax = 0.0, fiTax;
for(int i = 0; i < size; i++) //Initialize for loop
{
cout<<"Please enter your first name? " <<endl; //Display first name
cin>>firstName[i];
cout<<"Please enter your last name? " <<endl; //Display last name
cin>>lastName[i];
cout<<"How many hours did you work? " <<endl; //Dispaly hours worked
cin>>hoursWorked[i];
cout<<"What's the hourly rate? " <<endl; //Display hourly rate
cin>>hourlyRate[i];
if(hoursWorked[i] < 40)
{
gross[i] = hoursWorked[i] * hourlyRate[i];
}
else if( hoursWorked[i] > 40)
{
gross[i] = hoursWorked[i] * (hourlyRate[i] * timeHalf);
}
}
cout<<" \t\tXYX \n ";
cout<<"F-Name: L-Name: HorsWrked: HrlyRate: TimeHalf: S-Tax: F-Tax: Fica: Gross: Net: \n";
for(int i = 0; i < size; i++)
{
sTax = gross[i] * stateTax;
fTax = gross[i] * fedTax;
fiTax = gross[i] * fica;
totalTax = gross[i] * (stateTax + fedTax + fica);
timeHalf = 1.5;
net[i] = gross[i] - totalTax;
cout<<firstName[i]<<"\t " << setw(10) <<fixed <<setprecision(2) << lastName[i]<<"\t "
<< hoursWorked[i]<<"\t " <<hourlyRate[i] <<"\t " <<timeHalf<<"\t " <<sTax <<"\t "
<<fTax <<"\t " <<fiTax <<"\t " <<gross[i] <<"\t " <<net[i] <<"\t ";
}
}
Because in your conditions, you check if(hoursWorked[i] < 40) and if(hoursWorked[i] > 40), but there is no condition for if(hoursWorked[i] == 40). You probably wanted to use -or-equal operator on one of these conditions (>= or <=).

Calculating a new population

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.

Salary calculator (over time pay) require assistance of senior level programmers

4.16 (Salary Calculator) Develop a C++ program that uses a while statement to determine the
gross pay for each of several employees.
When someone works 41 hours or more. They get paid 1.5x more so my problem is that in my else if statement. I did rate * 1.5 which should translate into 10 * 1.5 = 15 but I get 425 because my code on the top probably, but I don't understand it at the moment.
He gave us this example. Which I'm trying to emulate.
"
Enter hours worked (-1 to end): 41
Enter hourly rate of the employee ($00.00): 10.00
Salary is $415.00
"
#include <iostream>
using namespace std;
int main()
{
double salary=0,rate=0,hours=0,counter=0;
cout << "Enter your hours worked: ";
cin >> hours;
cout << "Enter your rate: ";
cin >> rate;
while(counter<=hours)
{ salary=hours*rate;
counter++;
}
if(hours==-1)
{exit(0);
}
else if(hours>=41)
{
rate = rate * 1.5;
salary = salary + rate;
}
cout << "$" << salary;
return 0;
}
The loop you used has no functionality related to the problem, so I omitted it. Below is what will work. As others have said, define why you need a loop. I'm guessing you need to loop the code so the user can repeat this to their heart's content. If that is the case, I'll let you try to figure out how to break out of the loop when a user enters -1.
if (hours == -1)
exit(0);
else if (hours <= 40)
salary = rate * hours;
else {
double overtimeHours = hours - 40;
salary = rate * 40;
rate = rate * 1.5;
salary = salary + (rate * overtimeHours);
}
cout << "$" << salary;