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(||)
Related
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.
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've been trying to write a C++ program that calculates your end of year grade (an exercise given by the Google for Education C++ course). The program works, except for the fact that it doesn't calculate your final grade, instead, it just outputs "0". I have searched the code and can't seem to find the problem.
#include <iostream>
using namespace std;
int check(int a) {
if (!(cin >> a)) {
cout << "Come on, that isn't a score" << endl;
return 0;
}
}
int assignments() {
int assignment1 = 0;
int assignment2 = 0;
int assignment3 = 0;
int assignment4 = 0;
cout << "Enter the score for the first assignment. ";
check(assignment1);
cout << "Enter the score for the second assignment. ";
check(assignment2);
cout << "Enter the score for the third assignment. ";
check(assignment3);
cout << "Enter the score for the fourth assignment. ";
check(assignment4);
return ((assignment1 + assignment2 + assignment3 + assignment4) / 4 * 0.4);
}
int mid() {
int midterm = 0;
cout << "Enter the score for the midterm. ";
check(midterm);
return (midterm * 0.15);
}
int finalex() {
int finals = 0;
cout << "Enter the score for the final. ";
check(finals);
return (finals * 0.35);
}
int participation() {
int parti = 0;
cout << "Enter the class participation grade. ";
check(parti);
return (parti * 0.1);
}
int main() {
int assign = assignments();
int midt = mid();
int fingra = finalex();
int partigra = participation();
cout << "The final grade is: " << assign + midt + fingra + partigra << endl;
}
(The reason I have a different program for every grade type is because the course states that you should make as many functions as possible)
Either you should pass value to check() as reference or make check to return input value.
Change
int check(int a)
to
int check(int& a)
Second method
Modify check to
int check(int a) {
if (!(cin >> a)) {
cout << "Come on, that isn't a score" << endl;
return a;
}
}
And use return value to assign input to variables. Like
int midterm = 0;
cout << "Enter the score for the midterm. ";
midterm=check(midterm);
Your cin >> a statements updates value of a local variable which is gone as soon as check() returns. You want to update value of variables that are actually used for calculating grades. Just change the function check() to pass by reference check(int &a) or pass a pointer check(int *a)
hey guys new to this site looking some help for my final project i having to create a project that takes car data saves it to the heap and has a bunch of error checking not all the way done but getting there. but i cant grasp the heap and how to input it correctly into my code here is what i have. and it has to be under 175 lines and i still have to have it ask user if they want to write to a new file or existing. thanks ahead once again question is how do i create array on the heap able to hold the number of vech specified buy user.
#include <cstdlib>
#include <iostream>
#include <string>
using namespace std;
class carData4
{
public:
void setYear(int& year);
void setMake(string make);
void setModel(string);
void setMileage(int& mileage);
void setName(string name);
void setNumber(string number);
int getYear(){ return itsYear; }
string getMake(){ return itsMake; }
string getModel(){ return itsModel; }
int getMileage(){ return itsMileage; }
string getName(){ return itsName; }
string getNumber(){ return itsNumber; }
private:;
int itsYear;
string itsMake;
string itsModel;
int itsMileage;
string itsName;
string itsNumber;
};
void carData4::setYear(int & year)
{
do
{
cout << "Enter the cars Year from 1910 and 2014:\n ";
cin >> year;
itsYear = year;
if (year < 1910 || year > 2014)
cout << "INVALID! please enter a correct year! ";
} while (year < 1910 || year > 2014);
}
void carData4::setMake(string make)
{
cout << "Enter the cars make:\n\n";
cin >> make;
itsMake = make;
}
void carData4::setModel(string model)
{
cout << "Enter the cars model:\n\n";
cin >> model;
itsModel = model;
}
void carData4::setMileage(int & mileage)
{
do{
cout << "Enter the cars mileage:\n\n";
cin >> mileage;
itsMileage = mileage;
}
while (mileage <0 || mileage >10000000);
cout << "NOPE enter within 0 and million miles.\n\n";
cin >> mileage;
itsMileage = mileage;
}
void carData4::setName(string name)
{
cout << "Enter your name :";
cin >> name;
itsName = name;
}
void carData4::setNumber(string number)
{
cout << "Enter Your phone number (XXX)XXX-XXXX:";
cin >> number;
itsNumber = number;
}
int main()
{
carData4 car1;
int year, mileage, numCars, ;
string make, model, name, number;
cout << "How many vehicles are to be added to inventory?.\n\n";
cin >> numCars;
for (int i = 1; i < numCars; i++){
car1.setYear(year);
car1.setMake(make);
car1.setModel(model);
car1.setMileage(mileage);
car1.setName(name);
car1.setNumber(number);
cout << car1.getYear() << "\t" << car1.getMake() << "\t " << car1.getModel()
<< "\t" << car1.getMileage() << "\t " << car1.getName() << "\t " << car1.getNumber() << endl;
}
system("PAUSE");
return EXIT_SUCCESS;
}
i add some is this correct????????????????
int main()
{
carData4 car1; // *car1=new carData4[numCars];
int year,mileage,numCars;
double *cars;
string make,model,name,number;
cout << "How many vehicles are to be added to inventory?.\n\n";
cin >>numCars;
cars = new double [numCars];
for (int i=1; i<numCars;i++){
car1.setYear(year);
car1.setMake(make);
car1.setModel(model);
car1.setMileage(mileage);
car1.setName(name);
car1.setNumber(number);
cout << car1.getYear() << "\t" << car1.getMake() << "\t " << car1.getModel()
<< "\t" << car1.getMileage() << "\t " << car1.getName() << "\t " << car1.getNumber() <<endl;
delete [] cars;
}
system("PAUSE");
return EXIT_SUCCESS;
}
The best way to have dynamic storage for your use case would be to use a vector, like so:
std::cout << "How many vehicles are to be added to inventory?.\n\n";
std::size_t n;
std::cin >> n;
std::vector<carData4> cars ( n );
//gives you:
//cars[0] ... cars[ n-1 ]
http://en.cppreference.com/w/cpp/container/vector
To dynamically allocate an array based on user input:
unsigned int array_capacity;
cout << "Enter array capacity: ";
cin >> array_capacity;
int * my_array = new int[array_capacity];
Remember to delete the array using delete [] my_array;.
Edit 1: using Car class
CarData4 * my_cars = new CarData4[numCars];
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;