Loan calculator alteration - c++

I created a program that calculates loans, but it doesn't go under the guidelines of what my professor asked. Can show me the correct alteration. Source Code would be awesome and time saving, but you don't have to.
Heres the problem:
Write a program that lets the user enter the loan amount and the loan period in number of years and displays the monthly and total payments for each interest rate starting from 5% to 8%, with an increment of 1/8. Heres a sample run:
Loan amount: 10000 [Enter]
Numbers of Years: 5: [Enter]
Interest rate Monthly Payment Total Payment
5% 188.71 11322.74
5.125% 189.28 11357.13
Heres my previous code:
# include <iostream>
# include <iomanip>
# include <cmath>
using namespace std;
int main ()
{
double loanAmountA;
double annualRate;
double paymentAmount;
double amountInterest;
double ratePeriod;
double balanceAfter;
double amountApplied;
double balance;
double paymentPeriod;
int paymentsPerYear;
int totalPayments;
int loanCount = 1;
int paymentCount = 1;
bool anotherLoan = true;
char response;
while (anotherLoan == true)
{
cout<<"Enter amount of loan A:$ ";
cin>>loanAmountA;
cout<<endl;
cout<<"Enter annual percentage rate (APR): "<<"%";
cin>>annualRate;
cout<<endl;
cout<<"Enter the number of payments per year: ";
cin>>paymentsPerYear;
cout<<endl;
cout<<"Enter the total number of payments: ";
cin>>totalPayments;
cout<<endl;
cout<<"Payment Payment Amount Amount to Balance after";
cout<<endl;
cout<<"Number Amount Interest Principal This Payment";
cout<<endl;
cin.ignore(80,'\n');
while (paymentCount <=totalPayments)
{
annualRate = annualRate / 100;
balance = loanAmountA - totalPayments * paymentAmount;
ratePeriod = balance * annualRate;
paymentAmount = loanAmountA * (totalPayments / paymentsPerYear * annualRate) / totalPayments;
balanceAfter = balance - paymentAmount;
balance = loanAmountA - (paymentCount * paymentAmount);
cout<<left<<setprecision(0)<<setw(3)<<paymentCount;
cout<<setw(13)<<left<<fixed<<setprecision(2)<<paymentAmount;
cout<<setw(26)<<left<<fixed<<setprecision(2)<<ratePeriod;
cout<<setw(39)<<left<<fixed<<setprecision(2)<<balance;
cout<<setw(42)<<left<<fixed<<setprecision(2)<<balanceAfter;
if (paymentCount % 12 == 0)
{
cout<<endl;
cout<<"Hit <Enter> to continue: "<<endl;
cin.ignore(80,'\n');
cin.get();
}
paymentCount++;
loanCount++;
cout<<endl;
}
cout<<"Would you like to calculate another loan? y/n and <enter>";
cin>>response;
if (response == 'n')
{
anotherLoan = false;
cout<<endl<<endl;
cout<<"There were"<<loanCount<< "loans processed.";
cout<<endl<<endl;
}
}
return 0;
}

Did you try to use the debugger, and find the point of failure?

Related

I need to figure out simple loops for a school project [closed]

Closed. This question needs debugging details. It is not currently accepting answers.
Edit the question to include desired behavior, a specific problem or error, and the shortest code necessary to reproduce the problem. This will help others answer the question.
Closed 2 years ago.
Improve this question
We are supposed to make a retail sales cashier but I just can't figure out the loops at all. We have only learned simple selection and repetition statements so far and I know that's all I need but I just can't seem to figure it out.
Project Overview
Starter Code:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double cashDrawer = 500.00;
int productID = 0;
int quantity = 0;
double price = 0.0;
double subtotal = 0.0;
double salesTax = 0.0;
double totalSale = 0.0;
int anotherSale = 1;
// Loop for repeat sales
// Enter the first Product ID for the first sale (-1 to exit)
// Main loop for each sale
// Switch statement to determine the price, and calculate sales tax, if any, for the item.
// Get next Product ID
// Print properly formatted output for each sale
// Another sale?
// Display how much is in the cash drawer at the end
}
What I have so far:
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
double cashDrawer = 500.00;
int productID = 0;
int quantity = 0;
double price = 0.0;
double subTotal = 0.0; // for receipt purposes
double salesTax = 0.0; // for receipt purposes
double totalSale = 0.0; // for receipt purposes
int anotherSale = 1;
double taxRate = 0.075; // default tax rate
// Loop for repeat sales
while ()
{
// Enter the first Product ID for the first sale (-1 to exit)
cout << "Enter the first Product ID: ";
cin >> productID;
// Main loop for each sale
while (productID > 0)
{
// Switch statement to determine the price, and calculate sales tax, if any, for the item.
switch (productID)
{
case 101:
price = 65.00;
taxRate = 0.075;
break;
case 102:
price = 12.50;
taxRate = 0;
break;
case 103:
price = 24.50;
taxRate = 0.00;
break;
case 104:
price = 38.75;
taxRate = 0.075;
break;
case 105:
price = 17.80;
taxRate = 0.075;
break;
case 106:
price = 16.50;
taxRate = 0;
break;
case 107:
price = 42.85;
taxRate = 0.075;
break;
case 108:
price = 32.99;
taxRate = 0.075;
break;
case 109:
price = 28.75;
taxRate = 0.075;
break;
case 110:
price = 51.55;
taxRate = 0;
break;
default:
cout << "INVALID PRODUCT ID: Product ID not found." << endl;
}
cout << "Enter the quantity: ";
cin >> quantity;
subTotal += price * quantity;
salesTax += price * quantity * taxRate;
totalSale = subTotal + salesTax;
// Get next Product ID
cout << "Enter the next Product ID: ";
cin >> productID;
}
// Print properly formatted output for each sale
// Another sale?
}
// Display how much is in the cash drawer at the end
}
Any help is appreciated, thank you guys in advance.
The basic aspect of a loop statement is to repeat the same set of instructions until a specified condition is met. You have successfully figured it out for the inner loop of your code where you are checking if productID>0. You need to do the same for the outer loop and impose a similar condition on anotherSale i.e. while(anotherSale!=0). Every time the inner loop finish, just ask the user for the value of anotherSale; if the user enters 0, the loop should break.

Error in Output : C++ Carpet Store

I am working on an assignment in C++ but i am relatively new to the C++ programming language, however, I am getting errors in my output.
Question
The manager of the Crosswell Carpet Store has asked you to write a program to print customers’ bills. The manager has given you the following information:
The length and width of a room are expressed in terms of meters and centimeters. For example, the length might be reported as 16.7 meters.
The store does not sell fractions of a meter. Thus, the length and width must always be rounded up.
The carpet charge is equal to the number of square meters purchased times the carpet cost per square meter. Sales tax equal to 14% of the carpet cost must be added to the bill.
The labour cost is equal to the number of square meters purchased times R24.00, which is the labor cost per square meter. No tax is charged on labour.
Each customer is identified by a five-digit number, and that number should appear on the bill. Large-volume customers, identified by a customer number starting with a '0', may be given a discount. The discount applies to the cost before sales tax is added.
The sample output follows:
CROSWELL CARPET STORE STATEMENT
Customer name : xxxxx
Customer number : xxxxx
Carpet price : xx.xx
Labour : xx.xx
Subtotal : xx.xx
Less discount : xx.xx
Subtotal : xx.xx
Plus tax : xx.xx
Total : xx.xx
And my answer to this question is as follows:
#include <iostream>
#include <time.h>
#include <stdlib.h>
#include <stdio.h>
#include <math.h>
#include <string.h>
using namespace std;
int calculateCarpetSize (int length, int width)
{
int carpetSize;
carpetSize = ceil(length * width);
return carpetSize;
}
float calculateCarpetCost (int carpetSize , float sellingPrice)
{
float carpetCost;
carpetCost = carpetSize * sellingPrice;
return carpetCost;
}
float calculateLabourCost(int carpetSize)
{
float labourCost;
labourCost = carpetSize * 24.00;
return labourCost;
}
bool qualifyForDiscount(string customerNo)
{
string dis = "0";
if (customerNo.compare(0, dis.length(), dis) == 0)
{
return true;
}
else{
return false;
}
}
float computeDiscount ()
{
int discountPercentage;
float discount;
cout << "Enter the Percetage Discount: ";
cin >> discountPercentage ;
discount = discountPercentage / 100;
return discount;
}
void printCustomerStatement(string customerName, string customerNo, float carpetCost, float labourCost, float discount)
{
float subtotal = carpetCost + labourCost - discount;
float vat = subtotal*0.14;
cout << "\n CROSWELL CARPET STORE"<<endl;
cout << " STATEMENT"<<endl;
cout << "Customer name : "<<customerName<<endl;
cout << "Customer number : "<<customerNo <<'\n'<<endl;
cout << "Carpet price : "<<carpetCost<<endl;
cout << "Labour : "<<labourCost <<'\n'<<endl;
cout << "Subtotal : "<<carpetCost+labourCost<<endl;
cout << "Less discount : "<<discount <<'\n'<<endl;
cout << "Subtotal : "<<subtotal<<endl;
cout << "Plus Tax : "<<vat<<endl;
cout << "Total : "<<subtotal - vat<<endl;
}
int main()
{
string customerName;
string customerNo;
float carpetSize;
float sellingPrice;
float length;
float width;
float carpetCost;
float labourCost;
float discount;
cout <<"ENTER CUSTOMER NAME:";
cin >>customerName;
cout <<"ENTER CUSTOMER NUMBER:";
cin >>customerNo;
cout <<"ENTER ROOM WIDTH:";
cin >>width;
cout <<"ENTER ROOM LENGTH:";
cin >>length;
cout <<"ENTER SELLING PRICE:";
cin >>sellingPrice;
calculateCarpetSize(length, width);
calculateCarpetCost(carpetSize, sellingPrice);
calculateLabourCost(carpetSize);
if(qualifyForDiscount(customerNo))
{
computeDiscount();
}else
{
discount = 0.00;
}
printCustomerStatement(customerName, customerNo, carpetCost, labourCost, discount);
return 0;
}
I think the problem may be my function or my datatypes, or perhaps both.
EDIT
I get an output of this sort
ENTER CUSTOMER NAME:Quatban
ENTER CUSTOMER NUMBER:02234
ENTER ROOM WIDTH:20
ENTER ROOM LENGTH:20
ENTER SELLING PRICE:35
ENTER DISCOUNT PERCENTAGE: 2
CROSWELL CARPET STORE
STATEMENT
Customer name : Quatban
Customer number : 02234
Carpet price : 1.4e+004
Labour : 9.6e+003
Subtotal : 2.4e+004
Less discount : 0
Subtotal : 2.4e+004
Plus Tax : 3.3e+003
Total : 2e+004
First
Thus, the length and width must always be rounded up
Which means your function calculateCarpetSize should look more like :
int calculateCarpetSize (float length, float width)
{
int carpetSize;
carpetSize = ceil(length) * ceil(width);
return carpetSize;
}
Then
In your main :
calculateCarpetSize(length, width);
calculateCarpetCost(carpetSize, sellingPrice);
calculateLabourCost(carpetSize);
You should be storing the result of these functions like :
carpetSize = calculateCarpetSize(length, width);
carpetCost = calculateCarpetCost(carpetSize, sellingPrice);
labourCost = calculateLabourCost(carpetSize);
Edit
This actually gives you as output :
ENTER CUSTOMER NAME:Quatban
ENTER CUSTOMER NUMBER:02234
ENTER ROOM WIDTH:20
ENTER ROOM LENGTH:20
ENTER SELLING PRICE:35
Enter the Percetage Discount: 2
CROSWELL CARPET STORE
STATEMENT
Customer name : Quatban
Customer number : 02234
Carpet price : 14000
Labour : 9600
Subtotal : 23600
Less discount : 0
Subtotal : 23600
Plus Tax : 3304
Total : 20296
This looks like your (expected ?) result, even if I believe the last line should be subtotal + tax and not subtotal - tax but I may be wrong.

using functions to input 1 int and 1 string array and looping

i have a project for a cs class due late next week and ive got it almost done but i am having a few problems and ive been trying everything and cant get it to work. Our project consists of taking 3 months of 3 customers information and monthly utility charges from an input file, storing all of this in arrays, then calculating subtotals, tax, discount, and total paid then storing this into arrays, and then outputting 1 quarterly receipt for each customer. We have to do this using functions. my main problem is that it is only outputting the first customers receipt and ive double checked my for loop and to me it looks like it should work.
Thanks A lot
heres the output file
Austin City Office, Texas
RECEIPT #59, September28, 2013, 09:00PM
Customer ID: 127654
Name: Jack Jones
Address: 2059 Joe Lane, Austin TX, 78646
Phone Number: 512-520-5862
Electricity Charges: $6
Water Charges: $24
Gas Charges: $12
Subtotal: $42
Discount Amount: $0.84 (2% discount since your subtotal is less than $100)
Subtotal After the Discount: $41.16 (With 2% discount added)
Sales Tax Amount: $2.4696 (6% Tax since your subtotal after the discount is less than $100)
Total Amount Paid: $43.6296 (With 6% Sales Tax added)
.....................................................................................................
Refund Policy: 100% if an error is reported within 30 days from the date of payment. Only 75% refund
after 30 days.
Thank you for prompt payment.
heres my input file
Austin City Office, Texas
RECEIPT #59, September28, 2013, 09:00PM
Refund Policy: 100% if an error is reported within 30 days from the date of payment. Only 75% refund
after 30 days.
Thank you for prompt payment.
127654
Jack Jones
2059 Joe Lane, Austin TX, 78646
512-520-5862
2
8
4
2
8
4
2
8
4
Austin City Office, Texas
RECEIPT #59, September28, 2013, 09:00PM
Refund Policy: 100% if an error is reported within 30 days from the date of payment. Only 75% refund
after 30 days.
Thank you for prompt payment.
124325
Jack Williams
2788 Eagle Drive, Austin TX, 78646
512-623-7676
2
8
20
2
8
20
2
8
20
Austin City Office, Texas
RECEIPT #59, September28, 2013, 09:00PM
Refund Policy: 100% if an error is reported within 30 days from the date of payment. Only 75% refund
after 30 days.
Thank you for prompt payment.
125672
John Jones
3422 Hawk Drive, Austin TX, 78646
512-522-4564
2
8
40
2
8
40
2
8
40
and heres my code
#include<iostream>
#include<iomanip>
#include<string>
#include<string>
#include<fstream>
using namespace std;
//define varibles
int ncustomer1;
double discount, tax;
string dc, dsc, tc, dtpc;
//validation constant
const int MIN_N = 1, MAX_N = 3, MAX_TITLE=200, MAX_CINFO=200;
const float MIN_CHARGE=1.00, MAX_CHARGE= 1000.00;
// Array constant
const int MAX_NUMCUST=3, MAX_NUMMONTH=3, MAX_NUMCHARGE=3, MAX_NUMHEAD=6, MAX_NUMINFO=9, MAX_NUMTOTAL=8;
//customer info array
string NonNum[MAX_NUMCUST][MAX_NUMINFO];
//charges array
double Num[MAX_NUMCUST][MAX_NUMMONTH][MAX_NUMCHARGE] = {0};
//calculated array
double custTotals[MAX_NUMCUST][MAX_NUMTOTAL] = {0};
//functions
void input(string NonNum[MAX_NUMCUST][MAX_NUMINFO], double Num[MAX_NUMCUST][MAX_NUMMONTH][MAX_NUMCHARGE], int& count);
double subtotal(double custTotals[MAX_NUMCUST][MAX_NUMTOTAL], int&count);
double discount1(double custTotals[MAX_NUMCUST][MAX_NUMTOTAL], int&count);
double tax1(double custTotals[MAX_NUMCUST][MAX_NUMTOTAL], int&count);
void receipts(double custTotals[MAX_NUMCUST][MAX_NUMTOTAL], string NonNum[MAX_NUMCUST][MAX_NUMINFO], int&count);
int main()
{
//Ask number of customers from user
cout<< "Enter a number for amount of customers you would like to make a receipt for number should be between 1 and 3."<<endl;
cin >> ncustomer1;
//validate users entry
while(ncustomer1 > MAX_N || ncustomer1 < MIN_N )
{
cout << "Error: the number of customers must be between "<< MIN_N << " and "<< MAX_N <<endl;
cout<< "Re-Enter the number of customers"<<endl;
cin>> ncustomer1;
}
//output to screen when users entry is correct
cout<< "Ok, individual receipt(s) will be added to the output file for "<< ncustomer1<< " customer(s)."<<endl;
//customer for loop
for (int count = 0; count < ncustomer1; ++count)
{
input(NonNum, Num, count);
subtotal(custTotals, count);
discount1(custTotals, count);
tax1(custTotals, count);
receipts(custTotals, NonNum, count);
}
return 0;
}
//functions
void input(string NonNum[MAX_NUMCUST][MAX_NUMINFO], double Num[MAX_NUMCUST][MAX_NUMMONTH][MAX_NUMCHARGE], int& count)
{
//objects to help read input file
ifstream inputFile;
//open the input file
inputFile.open("Project5_a02418790_Input.txt");
//validation of input file
if(!inputFile)
{
cout<<"error opening input file.";
}
// For loop for non numeric data id, number...
for(int head = 0; head < 9; ++head)
{
//Get customer data as strings from input
getline(inputFile,NonNum[count][head]);
/* Validate inputed customer data
if(NonNum[count][head].length()>MAX_CINFO)
{
cout<<"customer "<<count<<"(customers are from 0-X, so customer 1=0) heading "<<head<<" String is too long"<<endl;
continue;
}
*/
}//end non numeric data for loop
//number of months For loop
for(int mnth = 0; mnth < 3; ++mnth)
{
//number of charges For loop
for(int charge = 0; charge < 3; ++charge)
{
//input charges
inputFile >> Num[count][mnth][charge];
//Running totals of the 3 charges
custTotals[count][charge] += Num[count][mnth][charge];
}//end of number of charges for loop
}//end of number of months foor loop
}
double subtotal(double custTotals[MAX_NUMCUST][MAX_NUMTOTAL], int&count)
{
// calculate the subtotal
//subtotal = Elec total + Water Total + Gas Total
custTotals[count][3]=custTotals[count][0]+custTotals[count][1]+custTotals[count][2];
}
double discount1(double custTotals[MAX_NUMCUST][MAX_NUMTOTAL], int&count)
{
//figure out the discount based on the subtotal
//if(subtotal=,<,> a number)
// discount%= x, comment= x;
if(custTotals[count][3]<100)
discount= .02, dc = "(2% discount since your subtotal is less than $100)", dsc="(With 2% discount added)";
if(custTotals[count][3]>=100&&custTotals[count][3]<250)
discount= .03, dc = "(3% discount since your subtotal is greater or equal to $100)", dsc="(With 3% discount added)";
if(custTotals[count][3]>=250&&custTotals[count][3]<500)
discount=.04, dc = "(4% discount since your subtotal is greater or equal to $250)", dsc="(With 4% discount added)";
if(custTotals[count][3]>=500)
discount=.05, dc = "(5% discount since subtotal is greater or equal to $500)", dsc="(With 5% discount added)";
//calculate the amount of discount
//discount amount = subtotal * discount %
custTotals[count][4] = custTotals[count][3]*discount;
//calculate the subtotal after the discount
//subtotal after dis= subtotal - discount
custTotals[count][5]=custTotals[count][3]-custTotals[count][4];
}
double tax1(double custTotals[MAX_NUMCUST][MAX_NUMTOTAL], int&count)
{
//figure out how sales tax percent and what captions
//if(subtotal after dis =,<,> a num)
// tax percent= x, comment= x;
if(custTotals[count][5]< 100 )
tax= .06, tc="(6% Tax since your subtotal after the discount is less than $100)", dtpc= "(With 6% Sales Tax added)";
if( custTotals[count][5] >=100&& custTotals[count][5] <250)
tax= .07, tc="(7% Tax since your subtotal after the discount is greater or equal to $100)", dtpc= "(With 7% Sales Tax added)";
if( custTotals[count][5] >=250&& custTotals[count][5] <500)
tax=.08, tc="(8% Tax since your subtotal after the discount is greater or equal to $250)", dtpc= "(With 8% Sales Tax added)";
if( custTotals[count][5] >=500)
tax=.09, tc="(9% Tax since your subtotal after the discount is greater or equal to $500)", dtpc= "(With 9% Sales Tax added)";
//calculate the sales tax amount
//amount of tax = subtotal after dis * tax percent
custTotals[count][6]= custTotals[count][5]*tax;
//calculate total amount paid
//total paid = subtotal after dis + amount of tax
custTotals[count][7]= custTotals[count][5] + custTotals[count][6];
}
void receipts(double custTotals[MAX_NUMCUST][MAX_NUMTOTAL], string NonNum[MAX_NUMCUST][MAX_NUMINFO], int&count)
{
//objects to help read output file
ofstream outputFile;
//open the output file
outputFile.open("Project5_a02418790_Output.txt");
//validation of output file
if(!outputFile)
{
cout<<"error opening output file.";
}
//OUTPUT ALL NEEDED INFO (STILL INSIDE CUSTOMER FOR LOOP)
//OUTPUT HEADER
outputFile<<setw(58)<<NonNum[count][0]<<endl<<setw(70)<<NonNum[count][1]<<endl;
//OUTPUT CUSTOMER INFO FOR LOOP
for(int z = 5; z < 9; ++z)
{
while(z == 5 )//Customer ID
{
outputFile<<endl<<"Customer ID: "<<NonNum[count][z]<< endl;
break;
}
while(z == 6 )//Name
{
outputFile<<"Name: "<<NonNum[count][z]<< endl;
break;
}
while(z == 7 )//Address
{
outputFile<<"Address: "<<NonNum[count][z]<< endl;
break;
}
while(z == 8 )//Phone Number
{
outputFile<<"Phone Number: "<<NonNum[count][z]<< endl;
break;
}
}//END OF OUTPUT CUSTOMER INFO FOR LOOP
//OUTPUT CHARGES AND TOTALS FOR LOOP
for(int y = 0; y < 8; ++y)
{
while(y == 0 )//Electricity Charges
{
outputFile<<endl<<"Electricity Charges: $"<<custTotals[count][y] << endl;
break;
}
while(y == 1 )//Water Charges
{
outputFile<<"Water Charges: $"<<custTotals[count][y] << endl;
break;
}
while(y == 2 )//Gas Charges
{
outputFile<<"Gas Charges: $"<<custTotals[count][y] << endl<<endl;
break;
}
while(y == 3 )//Subtotal
{
outputFile<<"Subtotal: $"<<custTotals[count][y] << endl;
break;
}
while(y == 4)//Discount Amount
{
outputFile<<"Discount Amount: $"<<custTotals[count][y]<<" "<<dc<< endl<<endl;
break;
}
while(y == 5 )//Subtotal After the Discount
{
outputFile<<"Subtotal After the Discount: $"<<custTotals[count][y]<<" "<<dsc<< endl<<endl;
break;
}
while(y == 6 )//Sales Tax Amount
{
outputFile<<"Sales Tax Amount: $"<<custTotals[count][y]<<" "<<tc<< endl<<endl;
break;
}
while(y == 7 )//Total Amount Paid
{
outputFile<<"Total Amount Paid: $"<<custTotals[count][y]<<" "<<dtpc<< endl<<endl;
break;
}
}//END OF OUTPUT CHARGES AND TOTALS FOR LOOP
//OUTPUT FOOTER BREAK
outputFile<<"....................................................................................................."<<endl;
//OUTPUT REFUND FOR LOOP
for(int w = 2; w < 4; ++w)
{
outputFile<< NonNum[count][w]<<endl;
}
//OUTPUT THANKYOU
outputFile<<setw(58)<<NonNum[count][4]<<endl;
//OUTPUT NEW LINE AND DIVIDER FOR NEW CUSTOMER
outputFile<<endl<<"_____________________________________________________________________________________________________"<<endl<<endl;
}
Are you sure it writes the first one each time? It looks to me that it would write the last one because you write over the file each call to receipt instead of appending to it.
The key reason to getting one set of outputs IMHO is this line
outputFile.open("Project5_a02418790_Output.txt");
Because you call it every call to receipts you end up overwriting the file each time and get just one set of outputs.
There are a lot of other things that are very bad coding practice.
Issue1: Use of arrays where you should use Structures / or classes:
For instance: You keep your customer information in arrays of arrays of strings.
std::string NonNum[MAX_NUMCUST][MAX_NUMINFO]
Then NonNum[1][5] is the ID of customerID of customer 1.. you should build a struct it will make your code much easier to understand. Name it properly NonNum tells us it contains strings which we know from glancing at the code, it doesn't tell us the important info of what kind of information is stores (Customer Id / Address etc..)
Also look at this:
for(int z = 5; z < 9; ++z) {
while(z == 5 )//Customer ID {
outputFile<<endl<<"Customer ID: "<<NonNum[count][z]<< endl;
break;
while(z==6) { ...
}
What is the point of the inner while? Why do you need to for loop? Wouldn't it be much easier to write:
outputFile<< "Customer ID:" << CustomerInfo[i].CustomerID << endl;
Issue2: Dependencies between functions
subtotal fills custTotals[i][3] and is dependent on custTotals[i][0], custTotals[i][1] & custTotals[i][2]
discount1 fills custTotals[i][4] based on the previous ones.. Again you are using an array where you should use a structure. But also it will make life much easier for you if the inputs and outputs to a function are clear and easy to understand.
Currently any change in the order of the functions will mess up the logic but it is impossible to see that from the code.
If you had a separate subTotals array that you would pass to subTotals so it would write to and then pass into Discount1 so it would read from everything becomes clearer.
Issue 3: you pass a int& count to all these functions although you do not plan to change it. I expected the error to be that you wrote to count in one of the inner function and didn't realize it. If you pass a non const ref to an object it indicates that this is a output of the function not an input.

Obtaining incorrect data using class object in different class

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;

Cant figure out how to calculate individual students totals in a loop

I am having an issue with this program. I need it to ask for a user id then ask for book code and then the cost of a book. An individual can enter an unknown number of books. the program needs to then calculate the individual students book total and then ask another student who does the same. the program must then display the grand totals and total number of books. I cant seem to figure out what to use to be able to keep track of the individual students entries. I would be able to do this from what I was reading about arrays. But we are not to that point yet. The professor wants us to do this with a loop. I am so lost, any help would be awesome.
#include <iostream>
#include <iomanip>
using namespace std;
int main ()
{
//Declare Variables.
int student_id;
char book_code;
float book_cost;
float tax_amount;
float book_subtotal;
const int SENTINEL = -9999;
const double TAX = .07;
float total_book_cost;
int number_books;
int total_books_sold;
double grand_total;
//Set Variables to Zero.
number_books = 0;
total_book_cost = 0.00;
grand_total = 0.00;
//Set Decimal to two places.
cout << fixed << showpoint;
cout << setprecision(2);
//Input Data
cout<<"Please enter your Student ID, then press enter."<<endl;
cin>>student_id;
while (student_id != SENTINEL){
cout<<"Please enter your Book Code, then press enter."<<endl;
cin>>book_code;
cout<<"Please enter the cost of the book, then press enter."<<endl;
cout<<"$"; cin>>book_cost;
tax_amount = book_cost * TAX;
book_subtotal = book_cost + tax_amount;
total_book_cost += book_subtotal;
number_books++;
cout<<"\tStudent Textbook Purchases Report"<<endl;
cout<<"********************************************"<<endl;
cout<<"Student"<<"\tBook"<<"\tBook"<<"\tTax"<<"\tBook"<<endl;
cout<<"Id"<<"\tCode"<<"\tCost"<<"\tAmount"<<"\tSubtotal"<<endl;
cout<<"--------------------------------------------"<<endl;
cout<<student_id<<setw(5)<<book_code<<setw(8)<<"$"<<book_cost<<
setw(3)<<"$"<<tax_amount<<setw(4)<<"$"<<book_subtotal<<endl;
cout<<endl;
cout<<"Total number of books purchased:"<<setw(8)<<number_books<<endl;
cout<<"Total books cost including tax:"<<setw(9)<<"$"<<total_book_cost<<endl;
cout<<"Please enter your Student ID, then press enter."<<endl;
cin>>student_id;
}
grand_total += total_book_cost;
total_books_sold += number_books;
cout<<"**************************************************"<<endl;
cout<<"Grand Totals:"<<endl;
cout<<"Total number of students who purchased books:"<<endl;
cout<<"Total number of books sold:"<<endl;
cout<<"Total cost of all books and taxes:"<<setw(9)<<"$"<<grand_total<<endl;
//Can put grand totals here
system("Pause");
return 0;
}
You could use the loop as this:
#include <iostream>
#include <iomanip>
using namespace std;
int main ()
{
//Set Decimal to two places.
cout << fixed << showpoint;
cout << setprecision(2);
int total_books_sold = 0;
double grand_total = 0.0;
const int SENTINEL = -9999;
int student_id = SENTINEL;
//Input Data
cout<<"Please enter your Student ID, then press enter."<<endl;
cin>>student_id;
while (student_id != SENTINEL){
double total_book_cost = 0.0;
int number_books = 0;
char book_code = '\0';
while (true)
{
cout<<"Please enter your Book Code, then press enter."<<endl;
cin>>book_code;
if (book_code == 'x')
break;
float book_cost;
cout<<"Please enter the cost of the book, then press enter."<<endl;
cout<<"$"; cin>>book_cost;
const double TAX = .07;
double tax_amount = book_cost * TAX;
double book_subtotal = book_cost + tax_amount;
total_book_cost += book_subtotal;
number_books++;
cout<<"\tStudent Textbook Purchases Report"<<endl;
cout<<"********************************************"<<endl;
cout<<"Student"<<"\tBook"<<"\tBook"<<"\tTax"<<"\tBook"<<endl;
cout<<"Id"<<"\tCode"<<"\tCost"<<"\tAmount"<<"\tSubtotal"<<endl;
cout<<"--------------------------------------------"<<endl;
cout<<student_id<<setw(5)<<book_code<<setw(8)<<"$"<<book_cost<<
setw(3)<<"$"<<tax_amount<<setw(4)<<"$"<<book_subtotal<<endl;
cout<<endl;
};
grand_total += total_book_cost;
total_books_sold += number_books;
cout<<"Total number of books purchased:"<<setw(8)<<number_books<<endl;
cout<<"Total books cost including tax:"<<setw(9)<<"$"<<total_book_cost<<endl;
cout<<"Please enter your Student ID, then press enter."<<endl;
cin>>student_id;
}
cout<<"**************************************************"<<endl;
cout<<"Grand Totals:"<<endl;
cout<<"Total number of students who purchased books:"<<endl;
cout<<"Total number of books sold:"<<endl;
cout<<"Total cost of all books and taxes:"<<setw(9)<<"$"<<grand_total<<endl;
//Can put grand totals here
system("Pause");
return 0;
}