Consider the following code:
#include <iostream>
using namespace std;
class inventory
{
public:
~inventory()
{
cout << "This Object is being destroyed" << endl;
}
inventory()
{
itemNumber = 0;
quantity= 0;
cost= 0;
}
inventory(int itemNumber1, int quantity1, double cost1)
{
setItemNumber(itemNumber1);
setQuantity(quantity1);
setCost(cost1);
}
void setItemNumber(int itemNumber2)
{
itemNumber=itemNumber2;
}
bool setQuantity(int quantity2)
{
bool userTrue = true;
bool userFalse = false;
if (quantity2 < 0)
{
quantity = 0;
return userFalse;
}
else
{
quantity= quantity2;
return userTrue;
}
}
bool setCost(double cost2)
{
bool userTrue = true;
bool userFalse = false;
if (cost2 < 0.0)
{
cost = 0.0;
return userFalse;
}
else
{
cost= cost2;
return userTrue;
}
}
double getTotalCost(int quantity, double cost)
{
int total;
total = (quantity * cost);
return total;
}
private:
int itemNumber;
int quantity;
double cost;
};
int main()
{
int itemNumberInput;
int quantityInput;
double costInput;
cout << "Enter the Item Number: " << endl;
cin >> itemNumberInput;
cout << "Enter the Quantity : " << endl;
cin >> quantityInput;
cout << "Enter the Cost : " << endl;
cin >> costInput;
inventory *pointerA, *pointerB;
pointerA = new inventory;
pointerB = new inventory(inventory(itemNumberInput , quantityInput , costInput));
inventory firstObject(itemNumberInput,quantityInput,costInput);
int itemNumberInput1;
int quantityInput1;
double costInput1;
cout << "Enter the Item Number: " << endl;
cin >> itemNumberInput1;
cout << "Enter the Quantity : " << endl;
cin >> quantityInput1;
cout << "Enter the Cost : " << endl;
cin >> costInput1;
inventory secondObject(itemNumberInput1,quantityInput1,costInput1); // not sure if thats correct
cout << secondObject.setItemNumber(); // not working
cout << secondObject.setQuantity(); // not working
cout << secondObject.setCost(); // not working
return 0;
}
The code above is supposed to take three user inputs, and send them to the classes, and the classes will do their job.
I'm currently stuck at the end where its giving me an error.
In the second object where the values are asked from the user, it should send these values to the classes.
Instead, I'm getting the error.
How can I resolve this problem?
Here is the fixed code:-
#include <iostream>
using namespace std;
class inventory
{
public:
~inventory()
{
cout << "This Object is being destroyed" << endl;
}
inventory()
{
itemNumber = 0;
quantity= 0;
cost= 0;
}
inventory(int itemNumber, int quantity, double cost)
{
this->itemNumber = itemNumber;
this->quantity = quantity;
this->cost = cost;
}
void setItemNumber(int itemNumber)
{
this->itemNumber=itemNumber;
}
bool setQuantity(int quantity)
{
bool userTrue = true;
bool userFalse = false;
if (quantity < 0)
{
this->quantity = 0;
return userFalse;
}
else
{
this->quantity= quantity;
return userTrue;
}
}
bool setCost(double cost)
{
bool userTrue = true;
bool userFalse = false;
if (cost < 0.0)
{
this->cost = 0.0;
return userFalse;
}
else
{
this->cost= cost;
return userTrue;
}
}
double getTotalCost(int quantity, double cost)
{
return quantity * cost;
}
private:
int itemNumber;
int quantity;
double cost;
};
int main()
{
int itemNumberInput;
int quantityInput;
double costInput;
cout << "Enter the Item Number: " << endl;
cin >> itemNumberInput;
cout << "Enter the Quantity : " << endl;
cin >> quantityInput;
cout << "Enter the Cost : " << endl;
cin >> costInput;
inventory *pointerA, *pointerB;
pointerA = new inventory;
pointerB = new inventory(inventory(itemNumberInput , quantityInput , costInput));
inventory firstObject(itemNumberInput,quantityInput,costInput);
int itemNumberInput1;
int quantityInput1;
double costInput1;
cout << "Enter the Item Number: " << endl;
cin >> itemNumberInput1;
cout << "Enter the Quantity : " << endl;
cin >> quantityInput1;
cout << "Enter the Cost : " << endl;
cin >> costInput1;
// The below line is correct
// inventory secondObject(itemNumberInput1,quantityInput1,costInput1);
//Alternatively
inventory secondObject;
secondObject.setItemNumber(itemNumberInput1);
secondObject.setQuantity(quantityInput1);
secondObject.setCost(costInput1);
delete pointerA; // delete dynamically allocated memory to avoid memory leak
delete pointerB;
return 0;
}
Well you've constructed 'secondObject' object using the 3-arg constructor, using the user-entered values as parameters. Therefore, the member variables of this object are being set via the constructor and using the 'set' methods aren't really necessary. In your case, the set methods would be useful if you wanted to change the values later on. For example, lets pretend the user enters 10, 10, and 2.5 for the values. You're then using the constructor to construct the object with those values. The only difference is you're placing those values into variables first. But it works the same way. If you wanted to change the value of quantity later on, you could do secondObject.setQuantity(2); And the quantity for that object is now set to 2. The reason why your calls to .set aren't working is because you need to pass in parameters to these methods i.e. the value you want to set it to.
In regard to the destructor method being printed, objects are destroyed when they go out of scope so that the memory is released. Normally, nothing would happen in terms of output- the object would just go out of scope and the compiler would free up the memory and go about its' business. However, you've coded a custom destructor that prints out 'The Object is being destroyed', which it is at the end of the main. It's likely your constructor is working fine, I'm just not sure what you expect to be happening. I'd also suggest you read up on memory leaks in C++, especially in regard to the 'new' keyword.
Related
I have a class Employees. I'm trying to make the user insert and delete an employee but it's not working. The size of the vectors should be 500.
class Employees{
public:
int maxx = 500;
vector<string> Surname;
vector<string> FirstName;
vector<string> birthdate;
int vacation[500];
public:
Employees() : Surname(500) {}
};
This is the function that inserts, but printing elements of the vectors is not working at all:
void Process(Employees ZZ){
string dateyear;
string datemonth;
string dateday;
int dateyear1;
int datemonth1;
int dateday1;
int Realage;
int Vacationi = 0;
for(int i = 0; i < 500; i++) {
string s;
cin >> s;
string d;
cin >> d;
string c;
cin >> c;
ZZ.Surname.push_back(s);
ZZ.FirstName.push_back(d);
ZZ.birthdate.push_back(c);
cout << endl << ZZ.Surname[1] << endl;
}
Now the delete function, if I input a string then search for it in the vector then get his index then delete, but the vector doesn't update any values.
void DeleteEmployee(Employees ZZ){
cout<< endl << ZZ.Surname[1] << endl ;
for (int i = 0; i < ZZ.Surname.size(); i++){
cout << ZZ.Surname[i] ;
}
cout << " delete employee";
string delete1;
cin >> delete1;
auto it = std::find(ZZ.Surname.begin(), ZZ.Surname.end(), delete1);
if (it == ZZ.Surname.end())
{
cout<< " name not in vector " << endl;
}
else
{
//auto index = distance(Names.begin(), find(Names.begin(), Names.end(), old_name_)));
//ZZ.Surname.erase(ZZ.Surname.begin()+index) ;
}
}
This is the main function, also the values of the vector are not printing:
int main()
{
Employees ZZ;
Process(ZZ);
DeleteEmployee(ZZ);
cout << "fyccck";
for (int i = 0; i < ZZ.Surname.size(); i++){
cout << ZZ.Surname[i] ;
}
}
There are a lot of things wrong with this code. But the particular issue you are asking about is caused by your functions passing the Employees object by value, so a copy is made, and any changes you make to the copy are not reflected in the original object in main().
You need to change the parameters to pass the Employees object by reference instead:
void Process(Employees &ZZ)
void DeleteEmployee(Employees &ZZ)
That being said, the whole design of the code is not good in general. The vectors are not being kept in sync properly, and for that matter you are using more vectors then you actually need, 1 single vector will suffice. And Process() and DeleteEmployee() should be members of the Employees class, not separate functions. And they are both accessing out-of-bounds of the Surname vector.
I would suggest completely rewriting the code from scratch, for instance something more like this:
struct Employee{
string Surname;
string FirstName;
string BirthDate;
int Vacation;
string DisplayName() const { return Surname + ", " + FirstName; }
};
class Employees{
public:
static const int maxx = 500;
vector<Employee> employees;
Employees() { employees.reserve(maxx); }
bool Add(const Employee &e);
bool Delete(string Surname, string FirstName);
};
bool Employees::Add(const Employee &e) {
if (employees.size() < maxx) {
employees.push_back(e);
return true;
}
return false;
}
bool Employees::Delete(string Surname, string FirstName) {
auto it = std::find_if(employees.begin(), employees.end(),
[&](const Employee &e){
return e.Surname == Surname && e.FirstName == FirstName;
}
);
if (it != employees.end()) {
employees.erase(it);
return true;
}
return false;
}
int main()
{
Employees ZZ;
for(int i = 0; i < Employees::maxx; ++i) {
Employee e;
cin >> e.Surname;
cin >> e.FirstName;
cin >> e.BirthDate;
e.Vacation = 0;//cin >> e.Vacation;
ZZ.Add(e);
cout << endl << e.DisplayName() << endl;
}
cout << " delete employee";
string Surname, FirstName;
if (cin >> Surname >> FirstName) {
if (ZZ.Delete(Surname, FirstName)) {
cout << " name deleted from vector " << endl;
} else {
cout << " name not in vector " << endl;
}
}
cout << "fyccck";
for (auto &e : ZZ.employees) {
cout << e.DisplayName() << endl;
}
return 0;
}
I'm trying to make a department store program for my school project.
I created a class array for the products to include their names, prices, stock, and number of purchased items to begin with.
But for some reason I get an error as a popup
"Exception thrown at 0x68665139 (vcruntime140d.dll) in Test project.exe:
0xC0000005: Access violation writing location 0x86A1ECD8."
Also, I get an error called error reading characters of string after execution.
Here's my code:
#include<iostream>
#include<string>
using namespace std;
class product {
private:
int stock; //items in stock
int add_stock; //added stock
int purchased; //purchased items(reduces stock)
string name; //name of item
float price; //price of item
public:
//fuctions to input all private variables
void setstock(int x) {
stock = x;
}
void setaddstock(int x) {
add_stock = x;
}
void setpurchased(int x) {
purchased = x;
}
void setname(string x) {
name = x;
}
void setprice(float x) {
price = x;
}
//functions to output all private variables
int getstock() {
return stock;
}
int getaddstock() {
return add_stock;
}
int getpurchased() {
return purchased;
}
string getname() {
return name;
}
float getprice() {
return price;
}
//function that restocks the items
void restock() {
stock += purchased;
}
//function that deducts purchased items from stock
void destock() {
if (stock >= purchased) {
stock -= purchased;
}
else { //in case the purchase demand exceeds items in stock
cout << "\nSorry we only have " << stock << "amount of left\n";
}
}
};
int main() {
int purchased;
product stuff[10]; //class array
int choice, total_qty = 0; //choice-> to choose between products,
total_qty-> total number of products purchased
char yesno; //to choose if user wants to buy anything
else (for do loop)
float total_price = 0; //total amount of money to be paid
// declaring product name and price
stuff[1].setname ("Coconut biscuits");
stuff[1].setprice (12.0);
stuff[2].setname ("Wai Wai noodles"); stuff[2].setprice (20.0);
stuff[3].setname ("Cadbury Dairy Milk"); stuff[3].setprice (45.5);
stuff[4].setname ("Lays"); stuff[4].setprice (50.0);
stuff[5].setname ("Rara Noodles"); stuff[5].setprice (18.5);
stuff[6].setname ("Khajurko Puff"); stuff[6].setprice (50.0);
stuff[7].setname ( "Nanglo Doughnut"); stuff[7].setprice (15.0);
stuff[8].setname ( "Nanglo whole-wheat bread"); stuff[8].setprice (65.0);
stuff[9].setname ("Dabur Real fruit juice"); stuff[9].setprice (30.0);
stuff[10].setname ("Coca-Cola"); stuff[10].setprice (35.5);
// declairing the number of items in stock and setting purchased = 0 for easy calculation
for (int i = 1; i <= 10; i++) {
stuff[i].setstock (100);
stuff[i].setpurchased (0);
}
// displays the menu, make purchase, repeat
cout << "What would you like to buy?\n\n\n";
do {
for (int i = 1; i <= 10; i++) {
cout << i << ". " << stuff[i].getname() << "\n\n"; //displays menu in format: 1. Biscuit
}
cout << "Enter your choice: ";
cin >> choice;
cout << "\n\nHow many of it would you like to buy?";
cin >> purchased;
stuff[choice].setpurchased(purchased);
stuff[choice].destock(); //function for destocking
cout << "\n\nWould you like to buy other items?";
cin >> yesno;
} while (yesno == 'y' || yesno == 'Y');
cout << "\n\n\n"; //line spacing, nothing cool here
//this for loop calculates total quantity and price as well as displays the receipt
for (int i = 1; i <= 10; i++) {
total_qty += stuff[i].getpurchased(); //total quantity
total_price += stuff[i].getpurchased() * stuff[i].getprice(); //total price
//only displays if stuff is purchased
if (stuff[i].getpurchased() > 0) {
//format: 1. Biscuit 4 10 40
cout << i << " " << stuff[i].getname() << " " << stuff[i].getpurchased() << " " << stuff[i].getprice() << " " << stuff[i].getpurchased()*stuff[i].getprice() << "\n";
}
}
// displays total price and quantity
cout << "\ntotal quantity: " << total_qty;
cout << "\ntotal price: " << total_price;
return 0;
}
for (int i = 1; i <= 10; i++)
should be
for (int i = 0; i < 10; i++)
You are exceeding your array of products.
I know this may be something obvious to some with experience but I am in the middle of my first real class for C++ programming. I have come across something in my code that I have been trying to resolve without any success. I am trying to extract the sum of the total value of "m_cost" stored within a array that is inside of these class modules. I want to output the total value inside of a switch statement for print out. Just seeing if someone can point me in the right direction or if I have completely gone off-track with the logic.
Project Code section in question:
void materialsMenu()
{
Inventory record[MAX_REC];
int i, n;
cout << "\n=====Inventory Management=====\n";
cout << "\nHow many Materials are there to be used? : ";
cin >> n;
cout << "Enter " << n << " Materials\n";
for (i = 0; i < n; i++)
record[i].getdata();
cout << "\n\n---Material Information---\n";
cout << "\n" << setw(8) << "Item Name "
<< setw(10) << " Price per foot "
<< setw(19) << " Cost " << endl;
cout << endl << "-------------------------------------------" << endl;
for (i = 0; i < n; i++)
record[i].showdata();
}
void Inventory::getdata() {
cout << endl;
cout << "\nEnter Material Name : ";
cin >> itemName;
cout << "Enter Price Per Foot : ";
cin >> ppf;
cout << "Enter Total Length Needed in Feet (ft) : ";
cin >> length;
cout << endl;
m_cost = ppf*length;
m_costT=???????? **this is the issue**
}
Materials.H file contents:
#ifndef MATERIALS_H
using namespace std;
class Materials {
private:
char itemName[15];
float ppf;
float length;
double m_cost;
float m_costT;
public:
Materials()
{
ppf = 0;
length = 0;
m_cost = 0;
m_costT = 0;
}
Materials(int itemName, float ppf, float length, double m_cost, float
m_costT)
{
length = getLength();
ppf = getPpf();
m_cost = getCost();
m_costT = getTotal();
}
float getLength()
{
return length;
}
float getPpf()
{
return ppf;
}
double getCost()
{
return m_cost;
}
float getTotal()
{
return m_costT;
}
void getdata();
void showdata();
};
#endif // !MATERIALS_H
Consider something like this to hold your records. It's very simple, but it demonstrates the idea of one class holding another and shows information hiding and all sorts of other tidbits. You are struggling to get that total because the Record class shouldn't care about this. The total is a concept outside of the scope of a Record. And as such, it is very difficult to calculate this from where you wanted to do it. (Though it is possible, it breaks all sorts of C++ rules and should be avoided)
Example:
class Record;
class RecordHolder
{
public:
int GetTotal()
{
int retVal = 0;
for(int i=0; i<10; i++) // Magic number 10 for demo purposes only...
{
retVal += records[i].m_cost; // Or use a public get function.
}
return retVal;
}
private:
Record records[10]; // Magic number 10 for demo purposes only...
};
The RecordHolder could also do printing, add/removing records, etc. It controls the records array. The Records are just Records and don't care about such management.
Hello I've ran into some trouble creating a GroceryItem class and using functions to accept and set input from a user.
Currently when I run the dataEntry function, the compiler moves on to the next function before accepting input from the first function.
I've created a test milk object to test my code but It doesn't allow me to enter data before moving to the next input prompt.
Once I can figure out the class functions, I will also create an array of objects and input values for such.
Any advice for how I can go about fixing this class and functions would be greatly appreciated!
#include <iostream>
using namespace std;
class GroceryItem{
private: int stockNumber;
double price = 0.0;
int quantity;
double totalValue;
double setPrice();
int setStockNum();
int setQuantity();
void setTotalValue();
public:
void dataEntry();
void displayValues();
};
int GroceryItem::setStockNum(){
int stock = 0;
cout << "Enter the stock number for the grocery item: ";
do {
cout << "Stock Number(1000-9999): ";
cin >> stock;
} while (!(stock >= 1000 && stock <= 9999));
stockNumber = stock;
return stockNumber;
}
double GroceryItem::setPrice(){
double x = 0.0;
cout << "Enter the price of the item: ";
while (!(x > 0)) {
cout << "Please enter a positive number for price!";
cin >> x;
}
price = x;
return price;
}
int GroceryItem::setQuantity(){
int x = 0;
cout << "Enter the quantity in stock: ";
while (!(x > 0)){
cout << "Please enter a positive number for quantity!";
cin >> x;
}
quantity = x;
return quantity;
}
void GroceryItem::setTotalValue(){
totalValue = (quantity * price);
}
void GroceryItem::dataEntry(){
setStockNum();
system("pause");
setPrice();
system("pause");
setQuantity();
system("pause");
setTotalValue();
}
void GroceryItem::displayValues(){
cout << "Stock number: " << stockNumber;
cout << "\nItem price: " << price;
cout << "\nQuantity on hand: " << quantity;
cout << "\nTotal value of item: " << totalValue;
}
int main(){
GroceryItem Milk;
Milk.dataEntry();
Milk.displayValues();
system("pause");
return 0;
}
Dude, pay attention to the condition of the while statement, the line
!(stock >= 1000 || stock <= 9999)
returns true for stock = 0 (always true, in this case), so the program won't enter the loop.
Maybe you meant something like:
!(stock >= 1000 && stock <= 9999)
AND(&&) not OR(||)
I don't understand why my code is not calculating the birthrate and the deathrate. I keep on getting 0 for both. I included the static_cast<double> to ensure this wouldn't happen. Any feedback / help?
#include <iostream>
#include <string>
using namespace std;
double calculateBirthRate();
double calculateDeathRate();
class PopInfo
{
private:
string cityName;
long totalCityPopulation;
int numberOfBirths;
int numberOfDeaths;
double birthrate;
double deathrate;
int bir;
int dea;
long citpop;
public:
PopInfo()
{
cityName = "";
totalCityPopulation = numberOfBirths = numberOfDeaths = 0;
}
long getPopulation()
{
return totalCityPopulation;
}
int getBirths()
{
return birthrate;
}
int getDeaths()
{
return deathrate;
}
string getCity()
{
return cityName;
}
void setCityName(string nameOfCity)
{
cityName = nameOfCity;
}
void setTotalCityPopulation(long populationOfCity)
{
totalCityPopulation = populationOfCity;
}
void setNumberOfBirths(int birthNumbers)
{
numberOfBirths = birthNumbers;
}
void setNumberOfDeaths(int deathNumbers)
{
numberOfDeaths = deathNumbers;
}
void calculateBirthRate(PopInfo);
void calculateDeathRate(PopInfo);
};
int main()
{
PopInfo newCity;
string cit;
long citpop;
int bir;
int dea;
cout << "What is the city name?: " << endl;
cin >> cit;
cout << "What is the total city population?: " << endl;
cin >> citpop;
while (citpop < 1)
{
cout << "Please enter a valid total city population: " << endl;
cin >> citpop;
}
cout << "What are the number of births?: " << endl;
cin >> bir;
while (bir < 0)
{
cout << "Please enter a valid number of births: " << endl;
cin >> bir;
}
cout << "What are the number of deaths?: " << endl;
cin >> dea;
while (dea < 0)
{
cout << "Please enter a vaild number of deaths: " << endl;
cin >> dea;
}
newCity.setCityName(cit);
newCity.setTotalCityPopulation(citpop);
newCity.setNumberOfBirths(bir);
newCity.setNumberOfDeaths(dea);
cout << endl;
cout << "The city name is " << newCity.getCity() << endl;
cout << "The total city population is " << newCity.getPopulation() << endl;
cout << "The birth rate is " << newCity.getBirths() << endl;
cout << "The death rate is " << newCity.getDeaths() << endl;
return 0;
}
void PopInfo::calculateBirthRate(PopInfo newCity)
{
double birthrate = static_cast<double>(newCity.bir) / newCity.citpop;
}
void PopInfo::calculateDeathRate(PopInfo newCity)
{
double deathrate = static_cast<double>(newCity.dea) / newCity.citpop;
}
You accidentally made birthrate and deathrate as local variables. Remove the leading keyword double, to make it:
void PopInfo::calculateBirthRate(PopInfo newCity)
{
birthrate = static_cast<double>(newCity.bir) / newCity.citpop;
}
void PopInfo::calculateDeathRate(PopInfo newCity)
{
deathrate = static_cast<double>(newCity.dea) / newCity.citpop;
}
Even so, it's kind of strange that you're passing newCity by value – did you mean to store the rates back in the same object, as in:
void PopInfo::calculateBirthRate(PopInfo& newCity)
{
newCity.birthrate = static_cast<double>(newCity.bir) / newCity.citpop;
}
void PopInfo::calculateDeathRate(PopInfo& newCity)
{
newCity.deathrate = static_cast<double>(newCity.dea) / newCity.citpop;
}
or did you mean to operate on the object in-place, as in:
void PopInfo::calculateBirthRate()
{
birthrate = static_cast<double>(bir) / citpop;
}
void PopInfo::calculateDeathRate()
{
deathrate = static_cast<double>(dea) / citpop;
}
I don't think you ever call the functions that calculate birth rate and death rate! That is on top of the issues already identified, but I'm pretty sure it matters... Put a cout debug statement in there and see if I'm right...
Another problem: since "rate" is a number between zero and 1, and your function getBirths returns an int, you are going to run into a rounding problem...
Also not sure you ever set dea and bir in the context of the class (you declare them at the main level). So many places where you are inviting problems...
The easiest solution would be to rewrite these two functions:
double getBirths()
{
return (double)numberOfBirths/citypop;
}
double getDeaths()
{
return (double)numberOfDeaths/citypop;
}
But read your code, and ask yourself what the scope of your variables is, where they are set (and if you ever set them...), where they are used, where you perform type conversions.... You can learn a lot from that.
EDIT
I couldn't help myself, and decided to copy your program and debug it. After a few simplifications in the structure I came up with the following (note I moved the two functions calculateBirthRate and calculateDeathRate inside the class definition for consistency; and I used the "internally known" variables totalCityPopulation etc, rather than some of the "alternative" ones you were using... it was getting very confusing. Finally, as I mentioned in the original answer - I made sure the birth and death rates were actually calculated. I have marked changed lines with //*** :
#include <iostream>
#include <string>
using namespace std;
double calculateBirthRate();
double calculateDeathRate();
class PopInfo
{
private:
string cityName;
long totalCityPopulation;
int numberOfBirths;
int numberOfDeaths;
double birthrate;
double deathrate;
int bir;
int dea;
long citpop;
public:
PopInfo()
{
cityName = "";
totalCityPopulation = numberOfBirths = numberOfDeaths = 0;
}
long getPopulation()
{
return totalCityPopulation;
}
double getBirths() //*** was int
{
return birthrate;
}
double getDeaths() //*** was int
{
return deathrate;
}
string getCity()
{
return cityName;
}
void setCityName(string nameOfCity)
{
cityName = nameOfCity;
}
void setTotalCityPopulation(long populationOfCity)
{
totalCityPopulation = populationOfCity;
}
void setNumberOfBirths(int birthNumbers)
{
numberOfBirths = birthNumbers;
}
void setNumberOfDeaths(int deathNumbers)
{
numberOfDeaths = deathNumbers;
}
//*** this function moved into the class definition
void calculateBirthRate()
{
birthrate = (double)numberOfBirths/totalCityPopulation; //*** using different variables
}
//*** this function moved into the class definition
void calculateDeathRate()
{
deathrate = (double)numberOfDeaths / totalCityPopulation; //*** using different variables
}
};
int main()
{
PopInfo newCity;
string cit;
long citpop;
int bir;
int dea;
cout << "What is the city name?: " << endl;
cin >> cit;
cout << "What is the total city population?: " << endl;
cin >> citpop;
while (citpop < 1)
{
cout << "Please enter a valid total city population: " << endl;
cin >> citpop;
}
cout << "What are the number of births?: " << endl;
cin >> bir;
while (bir < 0)
{
cout << "Please enter a valid number of births: " << endl;
cin >> bir;
}
cout << "What are the number of deaths?: " << endl;
cin >> dea;
while (dea < 0)
{
cout << "Please enter a vaild number of deaths: " << endl;
cin >> dea;
}
newCity.setCityName(cit);
newCity.setTotalCityPopulation(citpop);
newCity.setNumberOfBirths(bir);
newCity.setNumberOfDeaths(dea);
newCity.calculateBirthRate(); //*** added, or it's never calculated
newCity.calculateDeathRate(); //*** added, or it's never calculated
cout << endl;
cout << "The city name is " << newCity.getCity() << endl;
cout << "The total city population is " << newCity.getPopulation() << endl;
cout << "The birth rate is " << newCity.getBirths() << endl;
cout << "The death rate is " << newCity.getDeaths() << endl;
return 0;
}
When I run this code, I get the following:
What is the city name?:
Amsterdam
What is the total city population?:
1234567
What are the number of births?:
12345
What are the number of deaths?:
54321
The city name is Amsterdam
The total city population is 1234567
The birth rate is 0.00999946
The death rate is 0.044
The diff between your code and mine is:
33c33
< double getBirths()
---
> int getBirths()
38c38
< double getDeaths()
---
> int getDeaths()
68,71c68,69
< void calculateBirthRate()
< {
< birthrate = (double)numberOfBirths/totalCityPopulation;
< }
---
> void calculateBirthRate(PopInfo);
> void calculateDeathRate(PopInfo);
73,76d70
< void calculateDeathRate()
< {
< deathrate = (double)numberOfDeaths / totalCityPopulation;
< }
117,118d110
< newCity.calculateBirthRate();
< newCity.calculateDeathRate();
129a122,125
> void PopInfo::calculateBirthRate(PopInfo newCity)
> {
> double birthrate = static_cast<double>(newCity.bir) / newCity.citpop;
> }
130a127,130
> void PopInfo::calculateDeathRate(PopInfo newCity)
> {
> double deathrate = static_cast<double>(newCity.dea) / newCity.citpop;
> }
double birthrate = static_cast<double>(newCity.bir) / newCity.citpop;
...
double deathrate = static_cast<double>(newCity.dea) / newCity.citpop;
Here you are driving two new variable names birthrate and death rate. You're not writing the values two the class data members. Writing the type before the names overwrites it. To change, simply remove it.
birthrate = static_cast<double>(newCity.bir) / newCity.citpop;
...
deathrate = static_cast<double>(newCity.dea) / newCity.citpop;