In: Computer Science
Below is my code, Replace the 2 static_cast codes to a simpler C++ code. I would like to find another way to compile the program without using static_cast in my code. Thank you
#include <iostream>
#include <iomanip>
using namespace std;
class Population
{
private:
int population,
birth,
death;
public:
Population()
{
population = 2;
birth = 0;
death = 0;
}
Population(int x, int y, int z)
{
if (x < 2)
population = 0;
else
population = x;
if (y < 0)
birth = 0;
else
birth = y;
if (z < 0)
death = 0;
else
death = z;
}
void setPopulation(int x)
{
if (x < 2)
population = 0;
else
population = x;
}
void setBirth(int y)
{
if (y < 0)
birth = 0;
else
birth = y;
}
void setDeath(int z)
{
if (z < 0)
death = 0;
else
death = z;
}
double getBirth()
{
return static_cast<double>(birth) / population;
}
double getDeath()
{
return static_cast<double>(death) / population;
}
};
int main()
{
int population, birth, death;
cout << "What is the starting population: ";
cin >> population;
cout << "What is the amount of births: ";
cin >> birth;
cout << "What is the amount of deaths: ";
cin >> death;
Population place1(population, birth, death);
cout << fixed << setprecision(2);
cout << endl << "Birth rate is " <<
place1.getBirth() << endl;
cout << "Death rate is " << place1.getDeath() <<
endl;
return 0;
}
#include <iostream>
#include <iomanip>
using namespace std;
class Population
{
private:
int population,
birth,
death;
public:
Population()
{
population = 2;
birth = 0;
death = 0;
}
Population(int x, int y, int z)
{
if (x < 2)
population = 0;
else
population = x;
if (y < 0)
birth = 0;
else
birth = y;
if (z < 0)
death = 0;
else
death = z;
}
void setPopulation(int x)
{
if (x < 2)
population = 0;
else
population = x;
}
void setBirth(int y)
{
if (y < 0)
birth = 0;
else
birth = y;
}
void setDeath(int z)
{
if (z < 0)
death = 0;
else
death = z;
}
double getBirth()
{
// mulitply with double number so that it will be converted into
double
return (birth *1.0) / population;
}
double getDeath()
{
// mulitply with double number so that it will be converted into
double
return (death*1.0) / population;
}
};
int main()
{
int population, birth, death;
cout << "What is the starting population: ";
cin >> population;
cout << "What is the amount of births: ";
cin >> birth;
cout << "What is the amount of deaths: ";
cin >> death;
Population place1(population, birth, death);
cout << fixed << setprecision(2);
cout << endl << "Birth rate is " <<
place1.getBirth() << endl;
cout << "Death rate is " << place1.getDeath() <<
endl;
return 0;
}
Note : Please comment below if you have concerns. I am here to help you
If you like my answer please rate and help me it is very Imp for me