This question already has answers here:
Why does dividing two int not yield the right value when assigned to double?
(10 answers)
Closed 7 months ago.
I've been working on problems out of D.S. Malik C++ Programming book and I'm not looking for an answer but an explanation as to why in my charges function does billingAmount return 0 for incomeLow (Line 135). If I answer 70 for hourly rate, 15000 for customers income, and 75 for consulting time I should get $21.00
(70 * 40 * (45 / 60)) = $21.00
45 comes from subtracting 30 from 75 minutes since anything less than 30 minutes charges are free (0).
#include <iostream>
#include <iomanip>
using namespace std;
// Declared function identifiers
bool check_number(string str);
double hourly_rate();
double customer_income();
int consult_time();
double charges(double revenue, double rate, int time, bool incomeLow);
string tempRate;
string tempIncome;
string tempConsultTime;
int main()
{
int income = 0;
int consultTime = 0;
double hourlyRate = 0;
bool lowIncome = false;
hourlyRate = hourly_rate();
while (income <= 0)
{
income = customer_income();
}
if (income <= 25000) {
lowIncome = true;
}
consultTime = consult_time();
cout << fixed << showpoint << setprecision(2);
cout << "Billing Amount: "
<< charges(income, hourlyRate, consultTime, lowIncome)
<< "Low Income: " << lowIncome;
return 0;
}
bool check_number(string str) {
for (int i = 0; i < str.length(); i++) {
if (!isdigit(str[i])){
if (str[i] == '-'){
return false;
}
if (str[i] == '.'){
return true;
}
return false;
}
}
return true;
}
double hourly_rate()
{
cout << "Enter the hourly rate or 'n' to exit: ";
cin >> tempRate;
while(!check_number(tempRate))
{
if (tempRate[0] == 'n')
{
exit(0);
}
cout << "Error: Enter a positive hourly rate or 'n' to exit: ";
cin >> tempRate;
}
return stod(tempRate);
}
double customer_income()
{
cout << "Enter customers income or 'n' to exit: ";
cin >> tempIncome;
while(!check_number(tempIncome) || tempIncome == "0")
{
if (tempIncome[0] == 'n')
{
exit(0);
}
cout << "Error: Enter a positive integer or 'n' to exit: ";
cin >> tempIncome;
}
return stod(tempIncome);
}
int consult_time()
{
cout << "Enter the amount of consulting time (in minutes): ";
cin >> tempConsultTime;
while(!check_number(tempConsultTime))
{
if (tempConsultTime[0] == 'n')
{
exit(0);
}
cout << "Error: Enter a positive consult time (in minutes) or 'n' to exit: ";
cin >> tempConsultTime;
}
return stoi(tempConsultTime);
}
double charges(double revenue, double rate, int time, bool incomeLow){
double billingAmount;
int T;
if (incomeLow) {
if (revenue <= 25000 && time <= 30)
{
return 0;
} else if (revenue <= 25000 && time > 30) {
T = time - 30;
billingAmount = rate * 40 * (T / 60);
}
}
if (!incomeLow && time <= 20) {
return 0;
} else {
T = time - 30;
billingAmount = rate * 70 * (T / 60);
}
return billingAmount;
}
You obviously think that (45 / 60) is 0.75. In ordinary math it would be, but in C++ this is integer division and the result is always an integer (truncated towards zero). In effect 0.75 is rounded down to 0.
Just change (T / 60) to (T / 60.0) and you are no longer doing integer division and the result will be 0.75.
I'm trying to make it so that if the user chooses 1, it should increase the temp by 5, and decrease if the user chooses 2. the problem I'm having is that it doesn't update the value of the temperature.
UPDATE: I've finally got the math part to work but for some reason when i print the value of temperature it doesn't save the updates. If i do warmer, it's always at 20 and if i do cooler it's always at 10. I'm guessing i have to use the getTemp() because im only editing the local variable? How do I go about this?
#include <iostream>
using namespace std;
class heater
{
public:
int temperature;
int min;
int max;
int increment;
heater(int min=0, int max=60)
{
increment = 5;
temperature = 15;
}
int warmer(int);
int cooler(int);
int getTemp(int);
};
int heater::warmer(int temperature) {
if (temperature > (temperature - increment))
{
temperature += increment;
return temperature;
}
else cout << "Max temp reached.";
}
int heater::cooler(int temperature) {
if (temperature < (temperature + increment)){
temperature -= increment;
return temperature;
}
else cout << "Min temp reached.";
}
int heater::getTemp(int temperature) {
return temperature;
}
int main()
{
heater w;
heater c;
heater t;
heater g;
int i;
int number;
int temp;
for (i = 1; i != 0; i=1)
{
cout << "\n1. Warmer \n";
cout << "2. Cooler \n";
cout << "Press 0 to exit. \n";
cin >> number;
if (number == 1) {
temp = w.warmer(t.temperature);
cout << "The temperature is now: " << temp;
}
else if (number == 2) {
temp = c.cooler(t.temperature);
cout << "The temperature is now: " << temp;
}
else if (number == 0){
break;
}
}
return 0;
}
In int heater::warmer(int temperature) parameter named temperature shadows class member called temperature and you only modify that local parameter.
Simply remove that parameters and modify your class member:
#include <iostream>
using namespace std;
class heater
{
public:
int temperature;
heater()
{
temperature = 15;
}
int warmer();
int cooler();
int getTemp();
};
int heater::warmer() {
temperature -= 5;
}
int heater::cooler() {
temperature += 5;
}
int heater::getTemp() {
return temperature;
}
int main()
{
heater w;
heater c;
heater t;
int number;
cout << "1. Warmer \n";
cout << "2. Cooler \n";
cin >> number;
if (number == 1) {
w.warmer();
cout << "The temperature is now: " << t.temperature;
}
else if (number == 2) {
c.cooler();
cout << "The temperature is now: " << t.temperature;
}
return 0;
}
Also, the line heater getTemp(); doesn't do anything useful. It declares a global function that returns heater and takes no parameters. You probably wanted to call the member function like this:
cout << "The temperature is now: " << t.getTemp();
I'm having trouble refactoring this code into functions. What exactly am I supposed to enter for return to complete these last two functions. They include loops with total and subtotal with multiple calculations based on what character is entered. I understand the first two, just return the variable declared.
#include <iostream>
#include <iomanip>
using namespace std; // forgive me for being lazy!
double getPrice();
int getNumber();
double saleTotal(double getPrice, int getNumber);
void retail(double getPrice, int getNumber, double saleTotal);
const double TAX_RATE = .05;
int main()
{
double myPrice = getPrice();
int myNumber = getNumber();
double getTotal = saleTotal(myPrice, myNumber);
retail;
return 0;
}
double getPrice()
{
double price;
cout << "Enter price $";
cin >> price;
return price;
}
int getNumber()
{
int number;
cout << "Enter number purchased: ";
cin >> number;
return number;
}
double saleTotal(double getPrice, int getNumber)
{
char saleType;
double total;
double subTotal;
cout << "Type W if this is wholesale purchase. \n"
<< "Type R if this is retail purchase. \n"
<< "then press return... \n";
cin.ignore();
cin.get(saleType);
if ((saleType == 'W') || (saleType == 'w'))
{
total = getPrice * getNumber;
return total;
}
else if ((saleType == 'R') || (saleType == 'r'))
{
subTotal = getPrice * getNumber;
total = subTotal + subTotal * TAX_RATE;
return total;
}
else
{
cout << "Error in the input...";
}
}
void retail(double getPrice, int getNumber, double saleTotal)
{
char saleType;
cout << setprecision(2) << fixed << showpoint << getNumber << " items at $" << getPrice << endl;
cout << "Total bill $" << saleTotal;
if ((saleType == 'R') || (saleType == 'r'))
{
cout << " includes sales tax.\n";
}
return;
}
As the name of the methods suggest, you need:
double subTotal()
{
...
return mySubTotal;
}
and:
double total()
{
...
return total;
}
However in the total() method, saleType variable is used uninitialized, as #ThomasSablik commented, which means that your code invokes Undefined Behavior (UB) here:
if ((saleType == 'R') || (saleType == 'r'))
since you are checking an uninitialized variable in the conditions of this if statement.
subTotal() also invokes UB for the same reason. Initialize the variable.
Your functions subTotal(); and total don't know about myPrice and myNumber variables from main().
You declare new variables with the same names, but they are NOT connected to the original ones.
You need to pass those variables from main() into oter functions.
I'm unsure why when more than one transaction has been made the FOR LOOP won't iterate through the vector of "buyers". Am I missing something simple? I've spent the last few hours trying to fix this but to no avail. If any one could possibly help with my problem I'd be eternally grateful.
#include <iostream>
#include <iomanip>
#include <vector>
#include <cctype>
using namespace std;
//This class is for the car details that the user can purchase.
class cCar {
private:
string _sName;
double _dPrice;
public:
cCar(string s, double d)
{
_sName = s;
_dPrice = d;
}
string getName() { return _sName; }
double getPrice() { return _dPrice; }
};
//This is where all the car detail purchases are created and stored in the object 'carlist'
vector<cCar> CarDatabase(vector<cCar>& car_list)
{
car_list.push_back(cCar("Blue Nissan Skyline", 1000));
car_list.push_back(cCar("Red Mini", 3000));
car_list.push_back(cCar("Black Land Rover", 4000));
car_list.push_back(cCar("Beatle", 9000));
car_list.push_back(cCar("Ferrari", 300000));
return car_list;
}
//This class stores the user's transactions
class Finance {
private:
string _sUserName;
double _dCostOfCar;
string _sChosenCar;
int _iFinancePlan;
double _dDepositedAmount;
double _dMonthlyPayments;
double _dTotalLeftToPay;
public:
Finance(string sName, double dCostOfCar, string sChosenCar, int iFinancePlan, double dDepositedAmount, double dDMonthlyPayments, double dTotalLeftToPay)
{
_sUserName = sName;
_dCostOfCar = dCostOfCar;
_sChosenCar = sChosenCar;
_iFinancePlan = iFinancePlan;
_dDepositedAmount = dDepositedAmount;
_dMonthlyPayments = dDMonthlyPayments;
_dTotalLeftToPay = dTotalLeftToPay;
}
string getUserName() { return _sUserName; }
double getdCostOfCar() { return _dCostOfCar; }
string getChosenCar() { return _sChosenCar; }
int getFinancePlan() { return _iFinancePlan; }
double getDepositAmount() { return _dDepositedAmount; }
double getMonthlyAmount() { return _dMonthlyPayments; }
double getTotalLeftToPay() { return _dTotalLeftToPay; }
};
//1. This displays the car menu items.
void display_menu(vector<cCar>& car_list)
{
cout << "\nMENU";
for (int iCount = 0; iCount != car_list.size(); iCount++) {
cout << "\n" << iCount + 1 << ". " << car_list[iCount].getName();
cout << "\n\tPrice: £" << car_list[iCount].getPrice();
cout << "\n";
}
}
//This procedure proccesses the user's selection and all information regarding price and name of car are then transferred to transaction variables.
void selectedCar(vector<cCar>& car_list, string& sNameOfChosenCar, double& dCostOfChosenCar)
{
int iSelectionFromMenu = -1;
do {
cout << "\nChoose a car that you'd wish to buy from the menu (1 - " << car_list.size() << "): ";
cin >> iSelectionFromMenu;
if (iSelectionFromMenu > 0 && iSelectionFromMenu <= car_list.size()) {
sNameOfChosenCar = car_list[iSelectionFromMenu - 1].getName();
dCostOfChosenCar = car_list[iSelectionFromMenu - 1].getPrice();
}
else {
cout << "\nPlease enter valid number!";
iSelectionFromMenu = -1;
}
} while (iSelectionFromMenu == -1);
}
//This procedure gets from the user their preferred finance plan through their input.
void FinanceLength(int& iFinanceLength)
{
do {
cout << "\nHow long do you wish for your finance plan to last? (1 - 4 years): ";
cin >> iFinanceLength;
if (iFinanceLength < 0 || iFinanceLength > 4) {
cout << "\nOops, try again! Please enter between 1 - 4!";
}
} while (iFinanceLength < 0 || iFinanceLength > 4);
}
//This procedure gets the user's deposit.
void DepositMoney(double& dDepositAmount)
{
do {
cout << "\nEnter deposit amount (minimum £500 accepted): £";
cin >> dDepositAmount;
if (dDepositAmount < 500) {
cout << "\nTry again! Deposit an amount greater than or equal to £500.";
}
} while (dDepositAmount < 500);
}
//This function calculates the amount of money the user has to pay after deposit, added tax and charge percentage of 10%
double TotalLeftToPay(double iFinanceLength, double dDepositAmount, double dCostOfChosenCar)
{
double dChargePercentage = 0.10;
double dTotalLeftToPay = dCostOfChosenCar + (dCostOfChosenCar * dChargePercentage) - dDepositAmount + 135;
return dTotalLeftToPay;
}
//This calculates monthly payments.
double MonthlyPayments(double dTotalLeftToPay, int iFinanceLength)
{
double dMonthlyPayments = (dTotalLeftToPay / iFinanceLength) / 12;
return dMonthlyPayments;
}
//This asks the user whether they'd like to restart the application.
void RestartOptions(char& cOption, bool& bExit)
{
do {
cout << "\nDo you wish to make another purchase? (y/n): ";
cin >> cOption;
cOption = toupper(cOption);
switch (cOption) {
case 'Y':
bExit = false;
break;
case 'N':
bExit = true;
break;
default:
cout << "Sorry, that's an invalid input, please try again!";
continue;
}
} while (cOption != 'y' && cOption != 'Y' && cOption != 'n' && cOption != 'N');
}
//This string function returns either year or years (plural)
string YearOrYears(int iFinanceLength)
{
return (iFinanceLength > 1) ? "years" : "year";
}
//This displays receipt of the user's transaction.
//HERE IS WHRERE I "M STRUGGLING TO ITERATE
void Receipt(const string& sUserName, const int& iFinanceLength, const double& dDepositAmount, char cOption, bool& bExit, const string& sNameOfChosenCar, const double& dCostOfChosenCar, vector<Finance>& buyers)
{
double dTotalLeftToPay = TotalLeftToPay(iFinanceLength, dDepositAmount, dCostOfChosenCar);
double dMonthlyPayments = MonthlyPayments(dTotalLeftToPay, iFinanceLength);
buyers.push_back(Finance(sUserName, dCostOfChosenCar, sNameOfChosenCar, iFinanceLength, dDepositAmount, dMonthlyPayments, dTotalLeftToPay));
for (int iCount = 0; iCount != buyers.size(); iCount++) {
cout << "\nReceipt for: " << buyers[iCount].getUserName() << ". ";
cout << "\nYou have chosen " << buyers[iCount].getChosenCar() << ".";
cout << "\nYour finance plan timescale is " << buyers[iCount].getFinancePlan() << " " << YearOrYears(iFinanceLength) << ".";
cout << "\nYou've deposited £" << buyers[iCount].getDepositAmount() << ".";
cout << "\nTotal left to pay: £" << buyers[iCount].getTotalLeftToPay();
cout << "\nMonthly Payments: £" << buyers[iCount].getMonthlyAmount();
cout << "\n";
}
RestartOptions(cOption, bExit);
}
//This asks the user whether they're happy with the options of they've chosen.
void AcceptDeclineOptions(string& sUserName, int& iFinanceLength, double& dDepositAmount, bool& bExit, string& sNameOfChosenCar, double& dCostOfChosenCar, vector<Finance> buyers)
{
char cOption = 0;
do {
cout << "\nConfirm finance plan (y/n): ";
cin >> cOption;
cOption = toupper(cOption);
if (cOption == 'Y' || cOption == 'N') {
if (cOption == 'Y') {
Receipt(sUserName, iFinanceLength, dDepositAmount, cOption, bExit, sNameOfChosenCar, dCostOfChosenCar, buyers);
}
else {
RestartOptions(cOption, bExit);
}
}
else {
cout << "\nSorry, that's not a valid command.";
}
} while (cOption != 'Y' && cOption != 'N');
}
int main()
{
bool bExit = false;
int iFinanceLength = 0;
double dDepositAmount = 0;
string sNameOfChosenCar = "";
double dCostOfChosenCar = 0;
vector<cCar> car_list;
CarDatabase(car_list);
vector<cCar> car_purchases;
vector<Finance> buyers;
do {
cout << "Welcome!";
string sUserName = "";
cout << "\nEnter your name: ";
cin >> sUserName;
display_menu(car_list);
selectedCar(car_list, sNameOfChosenCar, dCostOfChosenCar);
FinanceLength(iFinanceLength);
DepositMoney(dDepositAmount);
AcceptDeclineOptions(sUserName, iFinanceLength, dDepositAmount, bExit, sNameOfChosenCar, dCostOfChosenCar, buyers);
} while (bExit == false);
}
I'm doing a project where we need to create a basic Zoo Tycoon game, in which we create a base class called Animal, 3 derived classes of Animal: Tiger, Penguin, Turtle. We also need to create a Zoo class that holds 3 separate arrays for each animal. I've written up my code but keep getting segmentation faults when compiling. I believe this is due to the way I create my object arrays as well as the method I use for inserting objects into them. I've uploaded my entire code. I apologize for the length. I didn't know what segment I could have uploaded to give a clear idea of what I'm doing.
This is my code
Animal.h
#ifndef ANIMAL_H
#define ANIMAL_H
class Animal
{
private:
int age;
double cost;
int numberOfBabies;
double baseFoodCost;
double payoff;
public:
Animal();
Animal(int, double, int, double, double);
int getAge();
void setAge(int);
double getCost();
void setCost(double);
int getNumberOfBabies();
void setNumberOfBabies(int);
double getBaseFoodCost();
void setBaseFoodCost(double);
double getPayoff();
void setPayoff(double);
};
#endif
Animal.cpp
#include "Animal.h"
Animal::Animal(int a, double c, int n, double b, double p)
{
age = a;
cost = c;
numberOfBabies = n;
baseFoodCost = b;
payoff = p;
}
int Animal::getAge()
{
return age;
}
void Animal::setAge(int a)
{
age = a;
}
double Animal::getCost()
{
return cost;
}
void Animal::setCost(double c)
{
cost = c;
}
int Animal::getNumberOfBabies()
{
return numberOfBabies;
}
void Animal::setNumberOfBabies(int n)
{
numberOfBabies = n;
}
double Animal::getBaseFoodCost()
{
return baseFoodCost;
}
void Animal::setBaseFoodCost(double b)
{
baseFoodCost = b;
}
double Animal::getPayoff()
{
return payoff;
}
void Animal::setPayoff(double p)
{
payoff = p;
}
Tiger.h
#ifndef TIGER_H
#define TIGER_H
#include "Animal.h"
class Tiger: public Animal
{
public:
Tiger();
Tiger(int, double, int, double, double);
};
#endif // !TIGER_H
Tiger.cpp
#include "Tiger.h"
Tiger::Tiger(int age, double cost, int numberOfBabies, double baseFoodCost, double payoff) : Animal(age, cost, numberOfBabies, baseFoodCost, payoff)
{
}
Penguin.h
#ifndef PENGUIN_H
#define PENGUIN_H
#include "Animal.h"
class Penguin: public Animal
{
public:
Penguin();
Penguin(int, double, int, double, double);
};
#endif
Penguin.cpp
#include "Penguin.h"
Penguin::Penguin(int age, double cost, int numberOfBabies, double baseFoodCost, double payoff) : Animal(age, cost, numberOfBabies, baseFoodCost, payoff)
{
}
Turtle.h
#ifndef TURTLE_H
#define TURTLE_H
#include "Animal.h"
class Turtle: public Animal
{
public:
Turtle();
Turtle(int, double, int, double, double);
};
#endif
Turtle.cpp
#include "Turtle.h"
Turtle::Turtle(int age, double cost, int numberOfBabies, double baseFoodCost, double payoff) : Animal(age, cost, numberOfBabies, baseFoodCost, payoff)
{
}
Zoo.h
#ifndef ZOO_H
#define ZOO_H
#include "Animal.h"
#include "Tiger.h"
#include "Penguin.h"
#include "Turtle.h"
#include <cstdlib>
#include <iostream>
using namespace std;
class Zoo
{
private:
Tiger **arrayTiger;
Penguin **arrayPenguin;
Turtle **arrayTurtle;
int sizeTiger, sizePenguin, sizeTurtle;
int capacityTiger, capacityPenguin, capacityTurtle;
double amount;
double revenue;
public:
Zoo();
Zoo(double);
void insertTiger(Tiger);
void insertPenguin(Penguin);
void insertTurtle(Turtle);
void Events();
double getAmount();
void setAmount(double);
void subtractAmount(double);
Tiger** getTigerArray();
Penguin** getPenguinArray();
Turtle** getTurtleArray();
void calculateRevenue();
double getRevenue();
void incrementAge();
void resetRevenue();
};
#endif
Zoo.cpp
#include "Zoo.h"
Zoo::Zoo(double a)
{
amount = a;
capacityTiger = 10;
capacityPenguin = 10;
capacityTurtle = 10;
sizeTiger = 0;
sizePenguin = 0;
sizeTurtle = 0;
revenue = 0;
arrayTiger = new Tiger*[capacityTiger];
arrayPenguin = new Penguin*[capacityPenguin];
arrayTurtle = new Turtle*[capacityTurtle];
}
void Zoo::insertTiger(Tiger t)
{
if (sizeTiger < capacityTiger)
{
arrayTiger[sizeTiger++] = &t;
}
else
{
int oldTigerCapacity = capacityTiger;
capacityTiger *= 2;
Tiger** newArrayTiger = new Tiger* [capacityTiger];
for (int i = 0; i < oldTigerCapacity; i++)
{
newArrayTiger[i] = arrayTiger[i];
}
delete[] arrayTiger;
arrayTiger = newArrayTiger;
arrayTiger[sizeTiger++] = &t;
}
}
void Zoo::insertPenguin(Penguin p)
{
if (sizePenguin < capacityPenguin)
{
arrayPenguin[sizePenguin++] = &p;
}
else
{
int oldPenguinCapacity = capacityPenguin;
capacityPenguin *= 2;
Penguin** newArrayPenguin = new Penguin* [capacityPenguin];
for (int i = 0; i < oldPenguinCapacity; i++)
{
newArrayPenguin[i] = arrayPenguin[i];
}
delete[] arrayPenguin;
arrayPenguin = newArrayPenguin;
arrayPenguin[sizePenguin++] = &p;
}
}
void Zoo::insertTurtle(Turtle turt)
{
if (sizeTurtle < capacityTurtle)
{
arrayTurtle[sizeTurtle++] = &turt;
}
else
{
int oldTurtleCapacity = capacityTurtle;
capacityTurtle *= 2;
Turtle** newArrayTurtle = new Turtle* [capacityTurtle];
for (int i = 0; i < oldTurtleCapacity; i++)
{
newArrayTurtle[i] = arrayTurtle[i];
}
delete[] arrayTurtle;
arrayTurtle = newArrayTurtle;
arrayTurtle[sizeTurtle++] = &turt;
}
}
void Zoo::subtractAmount(double a)
{
amount -= a;
}
double Zoo::getAmount()
{
return amount;
}
void Zoo::setAmount(double a)
{
amount += a;
}
void Zoo::Events()
{
int option = 0;
option = rand() % 4 + 1;
switch(option)
{
case 1: cout << "\n\nA sickness has occurred at the zoo." << endl << endl;
break;
case 2: cout << "\n\nThere has been a boom in zoo attendance." << endl << endl;
break;
case 3: cout << "\n\nA baby animal is born." << endl << endl;
break;
case 4: cout << "\n\nNothing happens." << endl << endl;
break;
}
}
Tiger** Zoo::getTigerArray()
{
return arrayTiger;
}
Penguin** Zoo::getPenguinArray()
{
return arrayPenguin;
}
Turtle** Zoo::getTurtleArray()
{
return arrayTurtle;
}
void Zoo::incrementAge()
{
for(int i = 0; i < sizeTiger; i++)
{
if((arrayTiger[i]->getCost()) == 10000)
{
arrayTiger[i]->setAge((arrayTiger[i]->getAge()) + 1);
}
}
for(int i = 0; i < sizePenguin; i++)
{
if((arrayPenguin[i]->getCost()) == 1000)
{
arrayPenguin[i]->setAge((arrayPenguin[i]->getAge()) + 1);
}
}
for(int i = 0; i < sizeTurtle; i++)
{
if((arrayTurtle[i]->getCost()) == 100)
{
arrayTurtle[i]->setAge((arrayTurtle[i]->getAge()) + 1);
}
}
}
void Zoo::calculateRevenue()
{
for (int i = 0; i < sizeTiger; i++)
{
revenue += (arrayTiger[i]->getPayoff());
}
for (int i = 0; i < sizePenguin; i++)
{
revenue += (arrayPenguin[i]->getPayoff());
}
for (int i = 0; i < sizeTurtle; i++)
{
revenue += (arrayPenguin[i]->getPayoff());
}
}
double Zoo::getRevenue()
{
return revenue;
}
void Zoo::resetRevenue()
{
revenue = 0;
}
main.cpp
#include "Animal.h"
#include "Penguin.h"
#include "Tiger.h"
#include "Turtle.h"
#include "Zoo.h"
#include <iostream>
using namespace std;
int main()
{
const int baseFeedingCost = 10;
Zoo z1(100000);
bool playGame = false;
bool menuExit = false;
char userStart, continueGame, loopPurchase, loopChoice = ' ';
int day = 0;
int initializer = 0;
cout << "\nWelcome to Zoo Tycoon!\n\nIn this game you will manage a zoo business." << endl;
while(!menuExit)
{
cout << "\nA: Play Game" << endl;
cout << "B: Exit" << endl;
cout << "\n\nPlease Select an option: ";
cin.get(userStart);
cin.ignore(INT_MAX, '\n');
if(userStart == 'A' || userStart == 'a') //user selected to start game
{
playGame = true;
menuExit = true;
cout << "\n\nYou will start with $" << z1.getAmount() << " in the bank." << endl;
cout << "\n\nTo begin your Zoo, you must purchase three types of animals (tigers, penguins, turtles)";
cout <<"\nin quantities of either 1 or 2." << endl << endl;
cout << "Please enter you desired number of tigers (1 or 2): ";
cin >> initializer;
if (initializer == 2)
{
Tiger t1(0, 10000, 1, 50, 2000);
z1.insertTiger(t1);
z1.subtractAmount(10000);
Tiger t2(0, 10000, 1, 50, 2000);
z1.insertTiger(t2);
z1.subtractAmount(10000);
cout << "\n\nYou will start with 2 tigers." << endl;
}
else if (initializer == 1)
{
Tiger t1(0, 10000, 1, 50, 2000);
z1.insertTiger(t1);
z1.subtractAmount(10000);
cout << "\nYou will start with 1 tiger." << endl;
}
cout << "\n\nPlease enter you desired number of penguins (1 or 2): ";
cin >> initializer;
if (initializer == 2)
{
Penguin p1(0, 1000, 5, 10, 100);
z1.insertPenguin(p1);
z1.subtractAmount(1000);
Penguin p2(0, 1000, 5, 10, 100);
z1.insertPenguin(p2);
z1.subtractAmount(1000);
cout << "\n\nYou will start with 2 penguins." << endl;
}
else if (initializer == 1)
{
Penguin p1(0, 1000, 5, 10, 100);
z1.insertPenguin(p1);
z1.subtractAmount(1000);
cout << "\n\nYou will start with 1 penguin." << endl;
}
cout << "\n\nPlease enter you desired number of turtles (1 or 2): ";
cin >> initializer;
if (initializer == 2)
{
Turtle tr1(0, 100, 10, 5, 5);
z1.insertTurtle(tr1);
z1.subtractAmount(100);
Turtle tr2(0, 100, 10, 5, 5);
z1.insertTurtle(tr2);
z1.subtractAmount(100);
cout << "\n\nYou will start with 2 turtles." << endl << endl;
}
else if (initializer == 1)
{
Turtle tr1(0, 100, 10, 5, 5);
z1.insertTurtle(tr1);
z1.subtractAmount(100);
cout << "\n\nYou will start with 1 turtle." << endl << endl;
}
cin.ignore(255, '\n');
cin.clear();
}
else if(userStart == 'B' || userStart == 'b')
{
cout << "\nThis game will now exit." << endl << endl;
menuExit = true;
}
else //user inputted invalid response
{
cout << "\n\nI'm sorry but your response is invalid. Please try again." << endl;
cin.ignore(255, '\n');
cin.clear();
}
}
while(playGame) //daily turns that ends when user enters false for playGame
{
loopChoice = loopPurchase = ' ';
z1.incrementAge();
cout << "\n\nDay: " << ++day << endl;
cout << "\nYou have $" << z1.getAmount() << " in the bank";
z1.Events();
cout << "\n\nWould you like to purchase an adult animal? ";
cin.get(loopPurchase);
cin.ignore(INT_MAX, '\n');
if(loopPurchase == 'Y' || loopPurchase == 'y')
{
cout << "\n\nA: Tiger" << endl;
cout << "B: Penguin" << endl;
cout << "C: Turtle" << endl;
cout << "\nPlease choose from the animals listed above: ";
cin.get(loopChoice);
cin.ignore(INT_MAX, '\n');
if(loopChoice == 'A' || loopChoice == 'a')
{
cout << "\n\nYou have chosen to purchase a Tiger" << endl;
Tiger tLoop(3, 10000, 1, 50, 2000);
z1.insertTiger(tLoop);
z1.subtractAmount(10000);
}
else if(loopChoice == 'B' || loopChoice == 'b')
{
cout << "\n\nYou have chosen to purchase a Penguin" << endl;
Penguin pLoop(3, 1000, 5, 10, 100);
z1.insertPenguin(pLoop);
z1.subtractAmount(1000);
}
else if(loopChoice == 'C' || loopChoice == 'c')
{
cout << "\n\nYou have chosen to purchase a Turtle" << endl;
Turtle trLoop(3, 100, 10, 5, 5);
z1.insertTurtle(trLoop);
z1.subtractAmount(100);
}
}
z1.calculateRevenue();
cout << "\n\nYour daily revenue is $" << z1.getRevenue();
//z1.setAmount((z1.getAmount()) + (z1.getProfit()));
z1.resetRevenue();
cout << "\n\nEnd of Day: " << day << ". Would you like to continue? (Enter yes or no): ";
cin.get(continueGame);
cin.ignore(INT_MAX, '\n');
if (continueGame == 'y' || continueGame == 'Y')
{
cout << "\nGame will continue. Proceeding to next day." << endl << endl;
}
else
{
cout << "\n\nYou have chosen to quit the game. Game will now exit." << endl << endl;
playGame = false;
}
}
return 0;
}
The code is huge. I have not reviewed everything.
In Zoo, you define your Animal arrays as:
Tiger **arrayTiger;
Penguin **arrayPenguin;
Turtle **arrayTurtle;
I don't know why a double pointer. Just *arrayTiger, etc. would work. You must also change the Insert method. Instead of assigning &t, just use t.
There are other improvements to make.
In Zoo, the insertTiger (etc), should also subtract amount. You always subtract the amount after calling insert, and you already know the price.
Your wrote almost the same code 3 times for the three animals when initializing arrays of animals. You could check if the input is 1 or 2 (to validate) and then insert animals in a for loop.
Finally. You are not reusing almost anything. You have a lot of repeated code for tigers, turtles and penguins.
Your code is too big as mentioned in the previous answer because of which I couldn't go through the entire code, but the segmentation fault you encounter could be because of the following piece of code :
void Zoo::calculateRevenue()
{
for (int i = 0; i < sizeTiger; i++)
{
revenue += (arrayTiger[i]->getPayoff());
}
for (int i = 0; i < sizePenguin; i++)
{
revenue += (arrayPenguin[i]->getPayoff());
}
for (int i = 0; i < sizeTurtle; i++)
{
revenue += (arrayPenguin[i]->getPayoff());
}
}
If you see here, in the third "for loop", you run the loop till sizeTurtle but are using the arrayPenguin for it. I think this is a mistake and what you wanted to do was something of this sort :
for (int i = 0; i < sizeTurtle; i++)
{
revenue += (arrayTurtle[i]->getPayoff());
}
That being said, they're could be other problems in the code that i am not aware of, but this certainly seems like a candidate to cause a crash in the program.