Obtaining incorrect data using class object in different class - c++

hey guys im writing a loan program here using two classes. I declare an object from my "MortCalc" Class in My LoanOfficer Class. The loan officer class is to determine whether a user qualifies for a loan or not a user enters the principal of a loan, monthly income, and monthly expenses. The Loan officer class then does a calculation and reports back to the user if the loan was approved using one rule. The rule is this: if the monthly payment of the loan( which is obtained from my MortCalc Class) and monthly expenses total is greater than 50% of the monthly income then the loan is not approved. The problem I've encountered is with calculating this. I try to store the calculation in a "rule" variable but it always equals 100 thus never approving the loan! obviously im doing something wrong here but i can't figure out what. here is my code:
LoanOfficer.h
class LoanOfficer
{
//private class variables
private:
MortCalc mc;
double intRate;
double monthlyIncome;
double term;
double monExpenses, principal;
double rule;
bool bLoanApprove, bOpen;
string userName, fileName,lenderName;
string loanOfficer, Welcome;
int counter;
void calculate();
LoanOfficer.cpp
LoanOfficer::LoanOfficer()
{
//initializing variables;
intRate = 4.1;
term = 30;
counter=1;
principal=0;
lenderName="John's Bank";
Welcome ="";
calculate();
}
void LoanOfficer::calculate()
{
rule = ((mc.GetMonPymt() + monExpenses) / monthlyIncome)* 100;
//i have a getter in my Mortcalc class which get's the monthly Payment.
}
bool LoanOfficer::isApproved()
{
if(rule>50)
{
bLoanApprove = true;
}
else{
bLoanApprove = false;
}
return bLoanApprove;
}
string LoanOfficer::getApproval()
{
if(bLoanApprove==true)
{
stringstream ss;
ss<<"\n\nLoan Approval Status: Yes"
<<"\nLoan amount: "
<<principal
<<"\nInterest Rate: "
<<intRate
<<"\nMonthly Payment: "
<<monPayment
<<"\nTotalLoan: "
<<mc.GetTotalLoan()
<<"\nTotal Interest"
<<mc.GetTotalInt()
<<"\n\nCongratulations We're looking to do business with you "
<<userName<<"!";
loanOfficer = ss.str();
}
else
{
stringstream ss;
ss<<"\n\nLoan Approval Status: No"
<<"\n\n Income vs Montly Payment and expenses does not meet "
<<"\n the 50% criteria net income that is necessary for this"
<<"\n institution to approve this loan";
loanOfficer = ss.str();
}
return loanOfficer;
}
void LoanOfficer::setPrincipal(double p)
{
mc.setPrin(p);
principal = p;
}
bool LoanOfficer::isOpen()
{
return bOpen;
}
void LoanOfficer::setMonInc(double mi)
{
monthlyIncome = mi;
}
void LoanOfficer::setExpenses(double ex)
{
monExpenses = ex;
}
void LoanOfficer::setAppName(string n)
{
userName = n;
}
string LoanOfficer::getFilename()
{
return fileName;
}
string LoanOfficer::getIntro()
{
stringstream ss;
ss<<"Hi Welcome to " <<lenderName
<<"\n Please enter your information below to see if you're approved for a loan."
<<"\nWe have a fixed interest rate of 4.1 and term of loan is 30 years."
<<"\nThe way we determine our loan approvals is by adding
loan payment and monthly expenses,"
<<"\nand that is greater than 50% of your monthly income the loan
is notapproved.\n\n";
Welcome = ss.str();
return Welcome;
}
void LoanOfficer::writeStatus()
{
stringstream ss;
ss<<userName<<"_"<<counter<<".txt";
fileName = ss.str();
ofstream receiptOut;
receiptOut.open(fileName.c_str());
//Writing report setting precision to 2 decimal places
//returning true if able to write receipt.
receiptOut<<" CUSTOMER LOAN INFORMATION "
<<month+1<<"/"<<day<<"/"<<year+1900<<"\n\n"
<<"********************************"
<<"\n Your Loan Information: "
<< "\n\n Principal: "<<"$" << fixed << setprecision (2)
<< principal
<< "\n\n Interest rate: "<< fixed << setprecision (2)
<< intRate << "%"
<< "\n\n Monthly Payment: "<<"$" << fixed << setprecision (2)
<< mc.GetMonPymt()
//here it obtains the correct monthly payment. I've checked through
//debugging.
<< "\n\n Total Interest paid: " <<"$"<< fixed << setprecision (2)
<< mc.GetTotalInt()
<<"\n\n Total Cost of the Loan: "<<"$" << fixed << setprecision (2)
<< mc.GetTotalLoan()
<<"\n*********************************"
<<"\n\n\nThank You for using my calculator. Have a Nice Day."
<<"\n****************************************************";
receiptOut.close();
counter++;
}
main.cpp
double principal,monthlyIncome,monthlyExpenses;
string name, answer;
string fAnswer
//class object
LoanOfficer lo;
cout<<lo.getIntro();
cout<<"Please enter your name: ";
cin>>name;
//passing name to setName class method.
lo.setAppName(name);
//start of do loop
do
{
//presenting the user a menu accessed from otherFunctions.cpp
//checking which choice user entered with switch statements
cout<<"\nPlease enter the amount you want to borrow: ";
cin>>principal;
cin.ignore();
lo.setPrincipal(principal);
cout<<"\nPlease enter your monthly income after taxes: ";
cin>>monthlyIncome;
cin.ignore();
lo.setMonInc(monthlyIncome);
cout<<"\nPlease enter your monthly expenses: ";
cin>>monthlyExpenses;
cin.ignore();
lo.setExpenses(monthlyExpenses);
cout<<lo.getApproval();
cout<<"\n\n Would you like to write a file? Enter y for yes and n for no\n";
cin>>fAnswer;
if(fAnswer =="y")
{
lo.writeStatus();
cout<<"\n\nReport is located in: "
<<lo.getFilename();
}
else
{
cout<<"\n\nNo report printed out.";
}
//ask if user would like to do another
cout<<"\n\nWould you like to do another loan? Enter y for yes and n for no\n";
cin>>answer;
cout<<"\n";
}while(answer =="y");
//end do/while
//Goodbye message
{
cout <<"\n Thanks for calculating. Goodbye!\n\n"; //when loop is done
}
return 0;
}

Change business logic!
You idea contradicts to your realization.
Let`s look closer at this statement in you question:
"The rule is this: if the monthly payment of the loan( which is obtained from my MortCalc Class) and monthly expenses total is greater than 50% of the monthly income then the loan is not approved. " and find place in your code where this business logic is implemented, here it is:
bool LoanOfficer::isApproved()
{
if(rule>50)
{
bLoanApprove = true;
}
else{
bLoanApprove = false;
}
from the code extract one can easily find that it contradicts your business logic.
Solution:
bool LoanOfficer::isApproved()
{
if(rule>50)
{
return false;
}
return true;

Related

c++ User input validation in sorted array

Hello i have a assinment that im making a weater program where we ask the user to enter info
first enter how many citys to use
then enter city name and degrees
then i will print out the list in order starting with the coldest city
and last i need to add a search funkar to search by degrees to find a location with that degrees
this one i havent started with
but my MAIN problem is that i need to validate that the user input is between -60 and 60 when enter the city and degrees... i just dont get it to work with anything... can someone please help out?`
cout<<"Enter Name of City and degrees \n\n";
for(i=0;i<n;i++){
cout<<"---------\n";
cin>>s_array[i].name;
cin>>s_array[i].degrees;
this is the code where user put in city and degree EX Rio 50
i just dont know how to validate it to be between -60 and 60`
What you're looking for, is simple data validation.
Assuming you have a struct City:
// used to hold the data
struct City {
string name;
double degrees;
};
and in your main(), you have initialised an array of these structs:
bool temperatureValid(const City);
int main() {
const int32_t totalCities = 12;
City cities[totalCities];
for (int32_t i = 0; i < totalCities; i++) {
// add data to structs
cout << "Enter city name: ";
cin >> cities[i].name; // you might want to validate this, too
cout << "Enter temperature: ";
cin >> cities[i].degrees;
cout << cities[i].name << " has a temperature of " << cities[i].degrees << "°" << endl;
if (temperatureValid(cities[i])) {
// cool... or not
} else {
cerr << "Invalid temperature range!" << endl;
--i; // make sure we can do this one again
continue;
}
}
return 0;
}
bool temperatureValid(const City city) {
return city.degrees >= -60 && city.degrees <= 60;
}
First of all, you should create a class. I understand from your code you must use class. If you don't have to it is easier than this. Then you should create an object.
Basic logic below here. You should create a class well.
class Weather //create class
Weather city // create object
cout<<"Please enter a city name:"<<endl;
cin>>city.name;
cout<<"Please enter a city degree:"<<endl;
cin>>city.degrees;

How do I calculate and display the correct percentage?

I am a C++ noob.
I am trying to work on this text-based game for school, and I am having trouble with displaying the correct percentage. I think this has to do with how I calculate it in the program, or I am screwing something up with the function.
I would be most grateful for some assistance. Cheers.
#include <string>
#include <cmath>
#include <iostream>
using namespace std;
double menu (float crew_count);
double calculatePct(float crew_count, float number_of_deaths)
{
double percent = ((crew_count - number_of_deaths) / crew_count) * 100;
}
double welcome ()
{
int crew_count;
string backstory = "\nYou are in charge of a top-secret military mission, when your\nspace ship makes an emergency landing, on the largest moon of planet Gork.\nThe space ship is damaged. Oxygen levels begin to drop.\nHow many military personnel are on your ship?\nNumber of personnel: ";
cout << backstory;
cin >> crew_count;
if (crew_count >= 1)
menu(crew_count);
else if (crew_count < 1)
cout << "\nThere must be 1 or more members of the crew! Please enter a valid number!\n";
}
double menu (float crew_count)
{
double percent;
double main_option;
cout << "\nChoose one:\n1. Attempt repairs on the ship.\n2. Request an emergency rescue from mission command.\n3. Break protocol and reveal the top-secret space ship's location,\nto the Russians on a nearby moon, asking for their assistance.\nYour choice: ";
cin >> main_option;
if (main_option == 1)
{
cout << "\nToxic material on the moon has corroded the launch gear, and the \nlaunch exploded!\n\nThere were no survivors.\n";
}
else if (main_option == 2)
{
cout << "\nThe oxygen was depleted before the rescue team arrived.\nThere were 4 people killed.\n";
if (crew_count <=4)
cout << "0% of crew members were rescued!\n";
else
float percent = calculatePct(crew_count, 4);
cout << percent << "% of the crew was rescued.\n";
}
else if (main_option == 3)
{
cout << "\nThe Russians agree to send a rescue ship, but secretly attempt to hack into the ships systems remotely, which triggers an automatic shut down of all\ncommunications systems and locks all mission critical storage units, including\none of the storage unit that holds emergency oxygen tanks.\n\nOne quarter of all personnel are lost.\n";
}
else if (main_option != 1, 2, 3)
{
cout << "\nYou have been eaten by a Grue!\n";
}
}
int main()
{
cout << "Welcome to Gork 1.0\nCreated by Cortez Phenix\nTo make selections, enter the number of each option!\n\n";
int choice;
cout << "What would you like to do?\n1. Play Game\n2. Exit\nYour Choice: ";
cin >> choice;
if (choice == 1)
welcome();
else if (choice == 2)
cout << "\nGoodbye!\n";
else
cout << "\nPlease choose 1 or 2.\n";
return 0;
}
Excuse me. I'm sure this post is hectic.
IMAGE: At the bottom, you can see the queer number
If we do some slight reformatting on parts of your code, it looks like this:
if (crew_count <=4)
cout << "0% of crew members were rescued!\n";
else
float percent = calculatePct(crew_count, 4);
cout << percent << "% of the crew was rescued.\n";
The value you print is not the value calculated by calculatePct, it's the indeterminate value of the percent variable defined earlier in the function.
In short: You forgot your curly-braces:
if (crew_count <=4)
cout << "0% of crew members were rescued!\n";
else
{ // Note curly brace here
float percent = calculatePct(crew_count, 4);
cout << percent << "% of the crew was rescued.\n";
} // And also here
I recommend you enable more verbose warnings, as the compiler should be able to detect that you use the uninitialized variable, as well as the new variable being initialized but not used.
you mixed intergers and floats and void
int crew_count then you fed double menu(float crew_count).
your menu function doesnt return anything its supossed to be void so does your welcome function
Also you calculatePct does not return the calculated percentage. Do that by adding return percent;
See if it helps

How can I fix my source code in my C++ program called Flix for Fun Profit Report?

I have coded a program in C++ for an assignment in my C++ Intro class but I have multiple errors in the program but I can't seem to figure out how to get all of the bugs out.
The program is supposed to ask the user for the name of the movie, the number of adult and child tickets sold, and calculate the gross box office profit, net box office profit and the amount paid to the distributor.
I can't seem to figure out how to initialize the variables adultTicketPrice and
childTicketPrice and I thought I declared them and am trying to figure out if they need to get initialized if I already declared them?
And how is the childTicket price out of scope?
And why am I getting the other errors and how can I fix them?
// Michael VanZant
// Flix for Fun Profit Report
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
// Create all double variables
double adultTicketsSold, childTicketsSold, grossBoxProfit, netBoxProfit,
amtPaidDist, adultTicketPrice, childTicketPrice
adultTicketPrice = 12;
childTicketPrice = 7;
cout << fixed << setprecision(2);
// Create the string variable
string movieName;
// Get the name of the movie and store it in the movieName string
cout << "What is the name of the movie?";
getline(cin, movieName);
cout << "\n";
// Cin.ignore to ignore the string variable type
cin.ignore();
// Get the amount of adult and child tickets sold
cout << "How many adult tickets do you want to buy?";
cin >> adultTicketsSold;
cout << "\n";
cout >> "How many child tickets did you want to buy?";
cin >> childTicketsSold;
cout << "\n";
// Calculate the amount of gross box office profit and display it
grossBoxProfit = (childTicketsSold * childTicketPrice) + (adultTicketsSold * adultTicketPrice);
cout << "Gross Box Office Profit: $" << grossBoxProfit;
cout << "\n";
// Calculate the net box profit amount and display it
netBoxProfit = grossBoxProfit * .20;
cout << "Net Box Profit Amount: $" << netBoxProfit;
cout << "\n";
// Calculate the amount paid to distributor and display it
amtPaidDist = grossBoxProfit - netBoxProfit;
cout << "Amount Paid to Distributor is: $" << amtPaidDist;
return 0;
}
When the compiler says "expected initialiser", it has nothing to do with these lines:
adultTicketPrice = 12;
childTicketPrice = 7;
which are actually assignments, not initialisations (though some old C terminology would call the first assignment an initialisation).
No, it's because it thinks you're still on this line, providing declarations and (optionally) initialisers:
double adultTicketsSold, childTicketsSold, grossBoxProfit, netBoxProfit,
amtPaidDist, adultTicketPrice, childTicketPrice
That's because you didn't put a ; at the end of it.
Also:
cout >> "How many child tickets did you want to buy?";
You meant <<.
Fixing those two little typos, the code compiles.

C++ passing variables in classes and getting logical errors

Here is the prompt I haven't gotten to all of it yet though:
Implement a class named GasPump that will be used to model a pump at a gas station.
A GasPump object should be able to perform the following tasks:
- Display the amount of gas dispensed
- Display the total amount charged for the amount of gas dispensed
- Set the cost per gallon on gas
- Display the cost per gallon of gas
- Reset the amount of gas dispensed and amount charged before each new usage
- Keep track of the amount of gas dispensed and the total charge
When implementing the GasPump class , you should assume that the gas pump dispenses
.10 gallons of gas per second. Write a test program in main() that prompts the user
to enter the cost per gallon of gas and how many seconds they want to pump gas for.
Then, display the number of gallons of gas pumped, the cost per gallon of gas, and
the total cost of the gas.
I am having problems calculating the amount paid and keep getting logical errors. As this code stands it will compile but it gives garbage for a calculation for amount charged.
#include <iostream>
#include <iomanip>
using namespace std;
class GasPump{
public:
void setCostPerGallon(double cpg){
costPerGallon = cpg;
}
double getCostPerGallon(){
return costPerGallon;
}
void setAmountDispensed(int seconds){
const double dispense = 0.10;
sec = seconds;
amountDispensed = dispense * sec;
}
int getAmountDispensed(){
return amountDispensed;
}
//here is the function I am having problems with, at least I think.
void setAmountCharged(double costPerGallon, double amountDispensed){
amountCharged = costPerGallon * amountDispensed;
}
double getAmountCharged(){
return amountCharged;
}
private:
double costPerGallon;
int sec;
double amountCharged, amountDispensed;
};
int main() {
double cpg = 0.0;
int seconds = 0;
GasPump pump;
cout << "Enter the cost per gallon of gas:";
cin >> cpg;
while(cpg <= 0.0) {
cout << "Enter a value greater than 0:";
cin >> cpg;
}
pump.setCostPerGallon(cpg);
cout << "Enter the amount of seconds you want to pump gas for:";
cin >> seconds;
while(seconds <= 0.0) {
cout << "Enter a value greater than 0:";
cin >> seconds;
}
pump.setAmountDispensed(seconds);
cout << "The gas pump dispensed " << pump.getAmountDispensed() << " gallons of gas." << endl
<< "At $" << pump.getCostPerGallon() << " per gallon, your total is $"
<< fixed << setprecision(2) << pump.getAmountCharged() << "." << endl;
return 0;
You never call pump.setAmountCharged(...), so the member variable amountCharged is whatever the compiler decided to initialize it to when you instantiated pump (typically 0);
To fix this, either get rid of the member variable amountCharged and do the calculation for the amount when getAmountCharged is called, or call setAmountCharged appropriately before calling getAmountCharged.
Here's the first solution:
class GasPump {
...
double getAmountCharged() {
return costPerGallon * amountDispensed;
}
...
};

double functions, fstreams, and more fun

The big picture is to take information from one file to another file. I've done that and it works well. The next thing I need to do is find the highest value from the new file. The basic format is like this: I have a bunch of "workers", I have the days they have worked, the hours & minutes they've worked. In the new file I have it formatted to show the pay rate (I enter the value as a cin) and then I have the total amount of money they made (everyone makes the same amount.. that which is in the cin). For some reason, I cannot make a function (that works) that will extract the persons name that makes the most money, and how much money that is. I got a little frustrated and was trying whatever I could so the new function is sloppy and ridiculous, but I was hoping you could help. To keep this a general question and not a specific question, I was wondering if you guys could just explain how to do something like this (finding the highest value & outputting it WITH the name of the person.. so essentially a double for the money and a string with the persons name) using parts of my code as an example:
#include <iostream>
#include <fstream>
#include <iomanip>
#include <string>
#include <cstdlib>
using namespace std;
void getandprintaddress (ifstream&, ofstream&); // this function will be used to get the data from one file and input it into the next with the total amount of money made from each person as well as the next function
double highestpaid(double& highesttotal, double& totalpay, string highestpaidemp, string name); // this function is what will be used to find the highest amount of money and the person who has it
void name(); // This is to input my name in the file.
struct employees // This is the structure with all of the information that will be used to calculate everything.
{
string name; // person's name
string highestpaidemp; // highest paid employee
string address; // the address of the employee
string address2;
int days; // days worked
int hours; //hours worked
double minutes; // minutes worked
int total_hours; // total hours worked
double totalpay; // total pay
double payrate; // pay rate
double total_minutes; // minutes worked
double total_time; // total hours and minutes worked
double highesttotal; // the highest total amount of money made between all employees.
};
int main(){
ifstream inputFile;
ofstream outputFile;
getandprintaddress(inputFile, outputFile);
return 0;
}
void getandprintaddress(ifstream& inputFile, ofstream& outputFile) // the main function that will be used to get and output all the information.
{
struct employees();
ifstream getdata;
ofstream outdata;
int employees_t;
employees employeeinfo;
string inputfile;
string outputfile;
cout << "What is the name of your input file? "<<endl; // this will be the file you open
cin>>inputfile;
getdata.open(inputfile.c_str());
if(getdata.fail()){ // this is meant to be used if someone enters a file that isn't there
cout << "The input file has failed to open. \n";
exit(1);
}
cout << "What is the name of your output file? \n"; // what you want the title of the new file to be.
cin>>outputfile;
outdata.open(outputfile.c_str());
if(outdata.fail())
{
//This is if the new file is invalid
cout << "The outputfile failed to open. \n";
exit(1);
}
cout << "How many employees are there? \n" ;
cin >> employees_t; // Enter how many employees there are
cout << "What is the employees hourly payrate? \n";
cin >> employeeinfo.payrate; // how much each employee makes.
for ( int info = 0; info < employees_t; info++)
{
employeeinfo.highesttotal = 0.0; // this will be needed for calculating the highest paid employee
employeeinfo.total_minutes = 0.0; // This is needed to calculate total minutes
employeeinfo.total_hours = 0; // Same as the total_minutes, but for hours instead.
employeeinfo.total_time = 0.0; // Needed to calculate total time
string line1;
getline(getdata, employeeinfo.name);
outdata << "Name: " << employeeinfo.name <<endl; // employees name
getline(getdata, employeeinfo.address);
outdata << "Address: \n"; // Employees address
outdata<< employeeinfo.address <<endl;
getline(getdata, employeeinfo.address2);
outdata <<employeeinfo.address2 <<endl;
getdata >> employeeinfo.days;
outdata << "Days worked: " <<employeeinfo.days << endl; // Days worked
for (int totalworked=0; totalworked<employeeinfo.days; totalworked++)
{
// Because the employees work different amount of days, this loop is needed to post the individual information from each employee
getdata >> employeeinfo.hours >> employeeinfo.minutes;
employeeinfo.minutes = employeeinfo.minutes / 60;
employeeinfo.total_hours = employeeinfo.total_hours + employeeinfo.hours;
employeeinfo.total_minutes = employeeinfo.total_minutes + employeeinfo.minutes;
employeeinfo.total_time = employeeinfo.total_minutes + employeeinfo.total_hours;
employeeinfo.totalpay = employeeinfo.total_time * employeeinfo.payrate;
outdata << employeeinfo.hours <<" hours "<< employeeinfo.minutes*60 << " minutes"<< endl;
}
outdata << fixed << showpoint << setprecision(1); // Setting the total hours worked to 1 decimal so that to include the minutes
outdata << "Total hours worked: "<<employeeinfo.total_time<<endl; // Total hours worked
outdata << fixed << showpoint << setprecision(2); // Setting the decimal to two places
outdata << "Hourly pay: $"<<employeeinfo.payrate << endl; //Hourly pay
outdata << "Gross pay: $" <<employeeinfo.totalpay <<endl; // Gross pay
getline(getdata,line1);
getline(getdata,line1);
outdata << "\n";
double highestpaid(employeeinfo.highesttotal, employeeinfo.totalpay);
}
};
double highestpaid(double& highesttotal, double&totalpay, string highestpaidemp, string name)
{
if (highesttotal < totalpay)
{
highesttotal = totalpay;
highestpaidemp = name;
}
return highestpaid(double& highesttotal, double&totalpay, string highestpaidemp, string name);
};
Ok, I'm going to answer your general question rather than spend too long searching through your code, but hopefully should work for both.
You have your struct employee
Stick them all in a vector of employees (which i'll call workers)
vector<struct employee> workers
using a vector means you can just keep on adding more to the end, but an array would work too if you had a fixed number of workers
now each worker can be identified by an integer index, 0 to n-1, where n is number of workers. Now can just iterate through (quicker methods if very large number of workers but probably fine here) to find highest salary
double highestPay = 0;
int highestPaidIndex = 0;
for(int i = 0; i++; i < n)
{
if(workers[i].totalpay > highestPay)
{
highestPay = workers[i].totalpay;
highestPaidIndex = i;
}
}
Now highestPaidIndex is the index of the highest paid employee, who has name workers[highestPaidIndex].name and total earnings workers[highestPaidIndex].totalpay
Hope that solves both your general and specific question