header and int main file - c++

so the program is going to calculate the total mile per hour during the trip. But however my total Mile per hour for a few trips is doubling instead of staying the same. Does anyone know why is that?
this is my head (.h) file
class Distance
{
public:
Distance() :
tripMiles(0.0), tripGallons(0.0),
totalMiles(0.0), totalGallons(0.0){}
void addTrip(double miles, double gallons)
{
tripMiles = miles;
tripGallons = gallons;
totalMiles += miles;
totalGallons += gallons;
}
double getTripMiles() const {return tripMiles;}
double getTripGallons() const {return tripGallons;}
double getMilesTotal() const {return totalMiles;}
double getGallonsTotal() const {return totalGallons;}
double getTripMPG() const {return tripMiles / tripGallons; }
double getTotalMPG() const {return totalMiles / totalGallons; }
private:
double tripMiles, tripGallons;
double totalMiles, totalGallons;
};
and this is my main file.
#include <iostream>
#include "Distance.h"
using namespace std;
int main()
{
Distance myDistance;
double miles= 0.0;
double gallons = 0.0;
cout << "Enter miles driven (-1 to quit): ";
cin >> miles;
myDistance.addTrip(miles,gallons);
while(miles != -1)
{
cout << "\nEnter Gallons used: ";
cin >> gallons;
myDistance.addTrip(miles,gallons);
cout << "\nMPG this trip: " << myDistance.getTripMPG();
cout << "\nTotal MPG is: " << myDistance.getTotalMPG();
cout << "\nEnter miles driven (-1 to quit): ";
cin >> miles;
}
}

You're calling myDistance.addTrip(miles,gallons); once before the loop starts, then again in the loop. This means you count the miles from the first trip twice. You should remove the first one.

Related

Math logic incorrect in function?

I am working on this exercise and it is pretty much complete but the math has to be wrong somewhere when calculating the senior citizen discount. The software that I use runs these two pieces of input to check the problem.
20
10
n
2
12 (which runs fine)
20
10
y
2
12 (does not not give me expected result)
This leads me to believe that the problem lies within the senior citizen discount part in the double determineMembershipCost function.
The expected result is "The membership cost = $162.80" but my code gives me "The membership cost = $152.00"
I am not sure what is wrong here. I'm hoping a second set of eyes can help find it. Thank you in advance.
Here is the code:
// headers
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
// prototypes
void displayGeneralInformation ();
void readNecessaryInformation (double& regularCostPerMonth,
double& costPerPersonalTrainingSession,
bool& seniorCitizen, int& numberOfSessions,
int& numberOfMonths);
double determineMembershipCost (double regularCostPerMonth,
double costPerPersonalTrainingSession,
bool seniorCitizen, int numberOfSessions,
int numberOfMonths);
// main
int main()
{
//variables
double regularCostPerMonth;
double costPerPersonalTrainingSession;
bool seniorCitizen;
int numberOfSessions;
int numberOfMonths;
double cost;
// print menu
// calls
// call displayGeneralInformation
displayGeneralInformation ();
// call readNecessaryInformation
readNecessaryInformation (regularCostPerMonth,
costPerPersonalTrainingSession,
seniorCitizen, numberOfSessions,
numberOfMonths);
// call determineMembershipCost
cost = determineMembershipCost (regularCostPerMonth, costPerPersonalTrainingSession, seniorCitizen, numberOfSessions, numberOfMonths);
// Display cost of membership
cout << "\nThe membership cost = $" << setprecision(2)<< fixed << cost << endl;
return 0;
}
// displayGeneralInformation function definition
void displayGeneralInformation ()
{
cout << "\nWelcome to Stay Healthy and Fit center." << endl;
cout << "This program determines the cost of a new membership." << endl;
cout << "If you are a senior citizen, then the discount is 30% off of the regular membership price." << endl;
cout << "If you buy membership for twelve months and pay today, the discount is 15%." << endl;
cout << "If you buy and pay for 6 or more personal training session today, the discount on each session is 20%." << endl;
}
// readNecessaryInformation function definition
void readNecessaryInformation (double& regularCostPerMonth,
double& costPerPersonalTrainingSession,
bool& seniorCitizen, int& numberOfSessions,
int& numberOfMonths)
{
cout << "\nEnter the cost of a regular membership per month: $";
cin >> regularCostPerMonth;
cout << "Enter the cost of one personal training session: $";
cin >> costPerPersonalTrainingSession;
cout << "Are you a senior citizen (Y,y/N,n): ";
char ch;
cin >> ch;
if (ch == 'Y' || ch == 'y')
seniorCitizen = true;
else
seniorCitizen = false;
cout << "Enter the number of personal training sessions bought: ";
cin >> numberOfSessions;
cout << "Enter the number of months you are paying for: ";
cin >> numberOfMonths;
}
// determineMembershipCost function definition
double determineMembershipCost (double regularCostPerMonth, double costPerPersonalTrainingSession, bool seniorCitizen, int numberOfSessions, int numberOfMonths)
{
double cost = regularCostPerMonth * numberOfMonths;
if (seniorCitizen)
{
cost = cost - (regularCostPerMonth * 0.30 * numberOfMonths);
}
if (numberOfMonths >= 12)
{
cost = cost - (regularCostPerMonth * 0.15 * numberOfMonths);
}
cost = cost + (costPerPersonalTrainingSession * numberOfSessions);
if (numberOfSessions > 5)
{
cost = cost - (costPerPersonalTrainingSession * 0.20 * numberOfSessions);
}
return cost;
}
Try this instead:
cost = (cost - (cost * 0.30)); //for 30% off
cost = (cost - (cost * 0.15)); //15% off

loops in headers or main file

So I put a while loop in my header file and I wanted to connect it to my main.cpp but then my main.cpp is not playing it unless it is stated like in my header file. So I'm wondering if a while loop in the header even necessary? The assignment is to create a program that calculates the user's salary given her sales.
This is my header file:
class Salary
{
public:
Salary(){};
Salary(double employeeSales, double employeeSalary)
:sales{employeeSales},salary(employeeSalary)
{
while(employeeSales != -1)
{
salary = 200 + (.09 * sales);
}
}
void setSales(double employeeSales)
{
sales = employeeSales;
}
void setSalary(double employeeSalary)
{
salary = employeeSalary;
}
double getSales() const{return sales;}
double getSalary() const{return salary;}
private:
double sales;
double salary;
};
this is my main.cpp
#include <iostream>
#include <iomanip>
#include "Salary.h"
using namespace std;
int main()
{
Salary mySalary;
double employeeSales;
double employeeSalary;
cout << fixed << setprecision(2);
cout << "Enter sales in dollars(-1 to quit): ";
cin >> employeeSales;
mySalary.setSales(employeeSales);
while(true)
{
employeeSalary = 200 + (.09 * employeeSales);
mySalary.setSalary(employeeSalary);
cout << "Salary is: $" << mySalary.getSalary();
cout << "Enter sales in dollars(-1 to quit): ";
cin >> employeeSales;
mySalary.setSales(employeeSales);
}
}
However the while loop in main won't work unless i put while(employeeSales != -1)
Rather than have your constructor handle garbage data (-1 as the argument), just create an if statement in the while-loop in main that breaks if the user entered -1.
while(true)
{
employeeSalary = 200 + (.09 * employeeSales);
mySalary.setSalary(employeeSalary);
cout << "Salary is: $" << mySalary.getSalary();
cout << "Enter sales in dollars(-1 to quit): ";
cin >> employeeSales;
if( employeeSales == -1)
{
cout << "Stopping program!" << endl;
break; // exits the while loop
}
mySalary.setSales(employeeSales);
}
Doing this allows for a while-loop in your Salary constructor to be unnecessary, and should hopefully solve your issue.

initialize class functions but output still 0

I am having problems with this program. When I compile it, I intialize all of the variables based upon the users input, but the cout still shows that the problem has '0' for most of the statements and for one of the statements its a '-negative' number. Any thoughts?
#include <iostream>
#include <conio.h>
#include <cmath>
#include <stdexcept>
using namespace std;
class MortgageCalc
{
protected:
float term;
public:
void setData(float, float, float);
float setTerm ();
float monthly;
float total;
float interest;
int years;
float loan;
};
void MortgageCalc::setData(float l, float i, float y)
{
loan = l;
interest = i;
years = y;
setTerm();
}
float MortgageCalc::setTerm()
{ //simple interest calculation with power calc to establish whole number translation
term = pow((1 + ((interest/100) / 12)), (12 * years));
return term;
}
class mPayment : public MortgageCalc
{
public:
int monthly()
{
return ((loan * ((interest/100) / 12) * term ) / (term - 1));
}
};
class tPayment : public mPayment
{
public:
int total()
{
return (monthly() * (years * 12));
}
};
class iPayment : public tPayment
{
public:
int plusInterest()
{
return (total() - loan);
}
};
int main()
{
double loan(0), interest(0);
int years = 0;
MortgageCalc mort1;
cout << "Enter the total loan amount on your mortgage loan: $"; //established loan variable
cin >> loan;
cout << "Enter the interest rate (in whole #'s only): "; //establishes interest rate variable
cin >> interest;
cout << "Enter the length of the loan in years: "; //establishes term of payments
cin >> years;
mort1.setData(loan, interest, years);
mPayment m;
cout << "Monthly payment due is " << m.monthly() << "." << endl;
tPayment t;
cout << "Total payment will be " << t.total() << "." << endl;
iPayment i;
cout << "Total payment plus Interest will be " << i.plusInterest() << "." << endl;
return 0;
};
You are taking all different objects like MortgageCalc mort1; mPayment m; tPayment t; iPayment i;.
These object do not have any relation.
Example:
mort1 = {term, monthly, total, interest, years, loan}
and suppose you have initialize with 1
mort1 = {term=1, monthly=1, total=1, interest=1, years=1, loan=1}
but it doesnot impact to the m because both are stored in memory on different location.
m = {term=0, monthly=0, total=0, interest=0, years=0, loan=0}
You can check both have different base address like cout<<&mort1<<endl<<&m; .
Data member you have set is part of MortgageCalc mort1 instead of mPayment m; tPayment t;.
You need to brush up your C++ basic's.
You use default constructors on those lines:
mPayment m;
tPayment t;
iPayment i;
They have no notion of previously input data held in mort1. You did not take care for any way to "share" or "communicate" this data.
m,t,i were all initialized with random data. There is no relation to mort1.
I won't go into details of what correct architecture here would be, but you should read about base class initialization. As a hint I'd say in your (a little weird) example you could try making this syntax work:
mPayment m(mort1);

no candidates for error compile error

I am trying to compile my application and it keeps running into "no match for 'operator<<'... it is not clear what the exact error of the program seems to be because he object is configured correctly as far as I can see.
#include <iostream>
#include <conio.h>
#include <cmath>
#include <stdexcept>
using namespace std;
class MortgageCalc
{
protected:
float term;
public:
void setData(float, float, float);
float setTerm ();
float monthly;
float total;
float interest;
float setLoan(void); //mutator
float setIntrest(void); //mutator
float setYears(void);
int years;
float loan;
};
void MortgageCalc::setData(float l, float i, float y)
{
loan = l;
interest = i;
years = y;
setTerm();
}
float MortgageCalc::setTerm()
{ //simple interest calculation with power calc to establish whole number translation
term = pow((1 + ((interest/100) / 12)), (12 * years));
return term;
}
float MortgageCalc::setLoan(void)
{ //returns loan amt to private member
return loan;
}
float MortgageCalc::setIntrest(void)
{ //returns interest amt to private member
return interest;
}
float MortgageCalc::setYears(void)
{ //returns years to private member
return years;
}
class mPayment : public MortgageCalc
{
public:
int monthly()
{
return ((loan * ((interest/100) / 12) * term ) / (term - 1));
}
};
class tPayment : public mPayment
{
public:
int total()
{
return (monthly() * (years * 12));
}
};
class iPayment : public tPayment
{
public:
int plusInterest()
{
return (total() - loan);
}
};
int main()
{
double loan(0), interest(0);
int years = 0;
MortgageCalc mort1;
cout << "Enter the total loan amount on your mortgage loan: $"; //established loan variable
cin >> loan;
cout << "Enter the interest rate (in whole #'s only): "; //establishes interest rate variable
cin >> interest;
cout << "Enter the length of the loan in years: "; //establishes term of payments
cin >> years;
mort1.setData(loan, interest, years);
mPayment m;
cout << "Monthly payment due is " << m.monthly() << "." << endl;
tPayment t;
cout << "Total payment will be " << t.total() << "." << endl;
iPayment i;
cout << "Total payment plus Interest will be " << i.plusInterest() << "." << endl;
return 0;
};
cout << "Total payment plus Interest will be " << i.plusInterest << "." << endl;
plusInterest is a class method pointer. Unsurprisingly, std::ostream has no clue what to do with a class method pointer, and is rightfully voicing its very strong objection, to such a preposterous proposition that it knows what to do with some strange class's method pointer.
You probably meant to write:
cout << "Total payment plus Interest will be " << i.plusInterest() << "." << endl;
Now, that's a proper function call, that returns an int, and std::ostream is now delighted to take this int, and do its magic with it.

Need help implementing functions in GroceryItem class

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