I can't get it to display the updated temperature - c++

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();

Related

Refactoring functions/using return. C++

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.

How to allow user input in objects and classes?

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.

C++ Segmentation fault when trying to insert derived objects into an Object Array

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.

Function/Syntax Errors

The goal of these functions in the end is to show someone's total fee's for being consulted, which is based off whether or not they have a low income. The functions are supposed flow downwards to get each needed value in order to calculate the total. I do not understand how to fix the various errors in my code, such as some variables not being declared in a specific scope, even though I thought i declared them correctly.
#include <iostream>
using namespace std;
const double HighIncomeRate = .7;
const double LowIncomeRate = .4;
bool isLowIncome();
int main() {
double Fee;
double ConsultTime;
cout << "Your fee is: " << getcalcFee(consultTime, Income) << endl;
return 0;
}
bool isLowIncome() {
double Income;
cout << "What is your income: " << endl;
cin >> Income;
cout << "How long have you been consulted" << endl;
cin >> ConsultTime;
if (Income <= 25000) {
return true;
} else {
return false;
}
}
double calcFee(int &ConsultTime, const double HighIncomeRate,
const double LowIncomeRate) {
if (isLowIncome == true) {
if (ConsultTime <= 30) {
calcFee = 0
} else {
calcFee = LowIncomeRate * 50((ConsultTime - 30) / 60)
}
}
if {
if (ConsultTime <= 20) {
calcFee = 0
} else {
calcFee = HighLowRate * 50((ConsultTime - 20) / 60)
}
}
return 0;
}

c++ Division . seemingly simple thing driving me crazy, advice please

Ok i've been programming for about a week now, i started with c++. I'm writing a program that is a kind of an arithmetic trainer, you enter the amount of equations you want, you enter your limit for the random number generator, you specify what kind of equations you want(/*-+), then the program uses a for loop and goes through and generates the equations and their answers in a var and then the users input is checked against this var and if they match another var which is counting the right answers is incremented. After the last equation the program tells the user how many they got right out of how many equations, and by dividing the amount of right answers by the amount of questions then multiplying this value by 100 u should obtain the accuracy percentage for this users arithmetic session. Problem is c++ keeps returning to me a friggin 0 value and i cannot for the life of me work out why in the world c++ is doing this.
entire program:
#include <iostream>
#include <string>
#include <ctime>
#include <cstdlib>
using namespace std;
void menu(void);
class session{
public:
session(){
create_session();
}
void create_session(void){
amount = 0;
range_limit = 0;
rights = 0;
answer = 0;
input = 0;
type = "";
while(amount == 0){
cout << "\nHow many equations do you want?: "; cin >> amount;
if(amount < 1){
cout << "\nAmount is too low!";
amount = 0;
}
}
while(range_limit == 0){
cout << "Enter the number range limit: "; cin >> range_limit;
if(range_limit < 1){
cout << "\nRange limit too low!";
range_limit = 0;
}
}
while(type == ""){
cout << "What equation type do you want?: "; cin >> type;
int strlen = type.size();
if(strlen < 1){
cout << "Invalid type input!";
type = "";
}
}
if(type == "+"){
for(int i=0;i<amount;i++){
int a = random();
int b = random();
answer = a + b;
cout << "\n" << a << " + " << b << " = "; cin >> input;
if(answer == input){
rights++;
}
}
}
cout << "\nYou got " << rights << " answers right out of " << amount << " equations." << endl;
cout << "Accuracy percentage: " << getAccuracy() << "%" << endl;
int post_menu=0;
while(post_menu == 0){
cout << "Enter 1 to create another session or 2 to return to the menu: ";
cin >> post_menu;
if(post_menu == 1){
create_session();
}else if(post_menu == 2){
menu();
}else{
cout << "Invalid input: ";
post_menu = 0;
}
}
}
float getAccuracy(){
float x = (rights/amount)*100;
return x;
}
int random(){
int x = 1+(rand()%range_limit);
return x;
}
void set_amount(int a){
amount = a;
}
void set_range_limit(int r){
range_limit = r;
}
void set_rights(int R){
rights = R;
}
void set_answer(int a){
answer = a;
}
void set_input(int i){
input = i;
}
void set_type(string t){
type = t;
}
private:
int amount;
int accuracy;
int range_limit;
int rights;
int answer;
int input;
string type;
};
int main(){
cout << "=== WELCOME TO ARITH! === \n=========================\n";
menu();
return 0;
}
void menu(void){
//Set the seed for random number gen.
srand(time(0));
//Set var for getting menu input, then get the menu input..
int menu_input;
cout << "\n[1]Create a Session. [2]Exit Arith. \nWhat would you like to do?: ";
cin >> menu_input;
//Now we check what the user wants and act accordingly..
if(menu_input > 2){
cout << "error";
menu_input=0;
}else if(menu_input == 1){
session start;
}else if(menu_input == 2){
cout << "\nExiting Arith!";
}else{
cout << "error";
menu_input=0;
}
}
Troublesome part:
float getAccuracy(){
float x = (rights/amount)*100;
return x;
some how the program is returning 0%.
anyone know why this is so and how to get the result im after.
rights and amount both are int , so when you divide the value is floored, for example if you do 5/2 the answer would be 2 instead of 2.5. To solve this you need to cast one of the variable to float like this: (float(rights)/amount) * 100.
when two int numbers are divided the result will also be int even if temporary variable. so you can make any of the variable float or double or cast it.
You need to convert only one data type because the other will be type promoted implicitly.
float x = ((double)rights/amount)*100;
or you can make your amount variable float by default if it doesnt affect any other part of your code.
Also you have the option to static cast:
float x = (static_cast<double>(rights)/amount)*100;