using functions to input 1 int and 1 string array and looping - c++
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.
Related
Logical error in outputting a room discount
I have been smashing my head against my keyboard for days and haven't gotten any help in any of my usual places. Someone please wave a wand and tell me what I'm doing wrong! When I run my code I get proper output for up to 19 rooms, once 20 is hit it's not outputting a discount. I have tried to rewrite the "if" statements several different ways and even went to a switch/break setup and it's the same issue every single time. I have a logical error and CANNOT find it! The assignment is "The cost of renting a room at a hotel is, say $100.00 per night. For special occasions, such as a wedding or conference, the hotel offers a special discount as follows. If the number of rooms booked is: at least 10, the discount is 10% at least 20, the discount is 20% at least 30, the discount is 30% Also if rooms are booked for at least three days, then there is an additional 5% discount. Instructions Write a program that prompts the user to enter: The cost of renting one room The number of rooms booked The number of days the rooms are booked The sales tax (as a percent). The program outputs: The cost of renting one room The discount on each room as a percent The number of rooms booked The number of days the rooms are booked The total cost of the rooms The sales tax The total billing amount. My code is #include<iostream> #include<`iomanip`> `using namespace std`; `int main`() { const float discount_10=0.10; const float discount_20=0.20; const float discount_30=0.30; const float additional_discount=0.05; cout << fixed << showpoint; cout << setprecision(2); //Variables double total_discount, final_bill, tax, base_cost, total_cost, room_cost, sales_tax; int num_rooms, num_of_days; cout<<"Enter the cost of renting one room: $"; cin>>base_cost; cout<<"Enter the number of rooms booked: "; cin>>num_rooms; cout<<"Enter number of days the rooms are booked: "; cin>>num_of_days; cout<<"Enter sales tax(%): "; cin>>sales_tax; if(num_rooms>=30) total_discount = discount_30; else if(num_rooms>=20 && num_rooms<=29) total_discount = discount_20; else if(num_rooms>=10 && num_rooms<=19) total_discount = discount_10; else if (num_rooms >=9) total_discount =0; if(num_of_days>=3) total_discount += additional_discount; else if (num_of_days<3) total_discount = 0; room_cost = (base_cost * num_of_days * num_rooms); //Total cost for all rooms total_cost = room_cost - (room_cost * total_discount); tax = total_cost * (sales_tax/100); //Final bill final_bill=total_cost+tax; cout<<"Cost of one room:" << base_cost <<endl; cout<<"Discount:" << total_discount *100<<"%"<<endl; cout<< "Rooms booked:" << num_rooms <<endl; cout<<"Days booked: " << num_of_days <<endl; cout<<"Total Cost: $" << total_cost<<endl; cout<<"Sales tax: "<<tax<< "%"<< endl; cout<<"Total bill: $" << final_bill << endl; return 0; } I've rewritten this thing about a dozen times and can't find it. I'm going nuts.
How can I fix my program's calculation and get it to run properly?
My code isn’t calculating. I tried for hours but it still showing 0.00 for gross taxes and union fee. and of course its not calculating the gross total and average. I’m at a lost where I went wrong. I reviewed so many example's of calculating with structs and I still cannot find as to why its showing 0. Here is my code : #include <iomanip> #include <string> using namespace std; struct Payroll { string f_name, l_name; char m_initial; int hrs_worked; double rate, gross, state_tax,fed_tax, union_fees,net; }; int main() { int size=0, num=20; Payroll workers[num]; double overtime, gross, fed, state, unionFees, net; double total_gross; cout<<"Enter the number of employees: ";// take input of number of employees cin >> num; //get employee's info cout<<"Enter details of employee " <<size+1<<": "<<endl; for (size =0; size < num; size ++) { //asking for user's input cout<<"Enter first name : "; cin >> workers[size].f_name; cout<<"Enter middle name initial: "; cin >> workers[size].m_initial; cout<<"Enter last name : "; cin >> workers[size].l_name; cout<<"Enter hours worked : "; cin >> workers[size].hrs_worked; //input validation while(workers[size].hrs_worked < 0 || workers[size].hrs_worked > 60) { cout<<"Error! Enter hours between 0 to 60: "; cin >> workers[size].hrs_worked; } cout<<"Enter Rate per hour : "; cin >> workers[size].rate; // input validation while(workers[size].rate <= 0 || workers[size].rate > 50) { cout<<"Error! Enter rate greater than 0 to 50: "; cin >> workers[size].rate; } cout<< endl; } // Calculating each employee's pay if(workers[size].hrs_worked > 40) { overtime = (workers[size].hrs_worked - 40) * workers[size].rate * 1.5; workers[size].gross = (workers[size].rate * 40) + overtime; } gross = (workers[size].rate * workers[size].hrs_worked); // calculate gross state = workers[size].gross * 6/100;// calculate state tax fed = workers[size].gross * 12/100;// calculate federal tax unionFees = workers[size].gross * 2/100;// calculate union fees net = workers[size].gross - (workers[size].state_tax + workers[size].fed_tax + workers[size].union_fees);// calculate net total_gross= workers[size].gross+total_gross; // display header cout<<"Data Housing Corp. Weekly Payroll"<<endl; cout<<setw(8)<<"FN"<<setw(4)<<"MI"<<setw(8)<<"LN"<<setw(8)<<"Hours"<<setw(6) <<"Rate"<<setw(8)<<"Gross"<<setw(6)<<"ST"<<setw(8)<<"FT"<<setw(8) <<"UF"<<setw(8)<<"Net"<<endl; cout<<setw(8)<<"==="<<setw(4)<<"==="<<setw(8)<<"==="<<setw(8)<<"===="<<setw(6) <<"===="<<setw(8)<<"===="<<setw(6)<<"==="<<setw(8)<<"==="<<setw(8) <<"==="<<setw(8)<<"===="<<endl; // displaying data for (size =0; size < num; size ++) { cout<<setw(8)<<workers[size].f_name<<setw(4); cout<<workers[size].m_initial<<setw(8); cout<<workers[size].l_name<<setw(6); cout<<workers[size].hrs_worked<<setw(8); cout<<fixed <<setprecision(2)<<workers[size].rate<<setw(8); cout<<fixed <<setprecision(2)<<workers[size].gross<<setw(8); cout<<fixed <<setprecision(2)<<state<<setw(8); cout<<fixed <<setprecision(2)<<fed<<setw(8); cout<<fixed <<setprecision(2)<<unionFees<<setw(8); cout<<fixed <<setprecision(2)<<net<<endl; } cout<<"========== =========== ========= ============= =========== ========"; cout<<" ============ ========= =========== ========== ==========\n"; cout<<"Total gross income of all employee= $"<<total_gross<<endl; cout<<"Average gross income of all employee= $"<<total_gross/num<<endl; cout<<"~~~~~~~~~~~~~~~~~~~~~~~~~~~\n"; return 0; } Enter the number of employees: 2 Enter details of employee 1: Enter first name : laaa Enter middle name initial: d Enter last name : daaaa Enter hours worked : 50 Enter Rate per hour : 10 Enter first name : rome Enter middle name initial: s Enter last name : italy Enter hours worked : 40 Enter Rate per hour : 10 Data Housing Corp. Weekly Payroll FN MI LN Hours Rate Gross ST FT UF Net === === === ==== ==== ==== === === === ==== laaa d daaaa 50 10.00 0.00 0.00 0.00 0.00 0.00 rome s italy 40 10.00 0.00 0.00 0.00 0.00 0.00 ========== =========== ========= ============= =========== ======== ============ ========= =========== ========== ========== Total gross income of all employee= $nan Average gross income of all employee= $nan ~~~~~~~~~~~~~~~~~~~~~~~~~~~
You should note that the conditional statement you have (if(workers[size].hrs_worked > 40)) is out of your for loop, yet you use that loop counter variable 'size' within that conditional statement. A few side notes: You need to initialize 'workers[size].gross' even if the 'workers[size].hrs_worked' attribute is <= 40. It seems as though an array isn't an ideal option over here (unless you use dynamic memory allocation) since you are initializing the size of the array at runtime. Not sure how your compiler is allowing you to do this? 'total_gross' is uninitialized but you use it in some arithmetic down the line; clarify its use and the other local variable's use as well. You should be able to take it from here; happy coding!
C++, Interest Calculator not displaying correct output
The question asks "Write a program that reads an initial investment balance and an interest rate, then prints the number of years it takes for the investment to reach one million dollars." The inputs I've been putting in are 100 for amount, and 3 for interest rate. But when i compile and run, the output is 29 which is incorrect as the amount is only 187 which isn't at all close to a million. /* Question: Write a program that reads an initial investment balance and an interest rate, then prints the number of years it takes for the investment to reach one million dollars. */ #include <iostream> using namespace std; int main() { //Obtain user amount double amount; cout << "Please enter an initial investment balance ($0.00): $"; cin >> amount; //Obtain user interest rate double interest_rate; cout << "Please enter an interest rate: "; cin >> interest_rate; //Convert interest rate to decimal interest_rate = interest_rate / 100; int time = 1; //Calculate how many years while (amount < 1000000) { amount = amount * (1 + (interest_rate * time)); ++time; } //Display years cout << "Years to reach one million: " << time; return 0; } The output i am expecting is: "Years to reach one million: 333300" since 333300 is exactly one million.
In one year, the amount will grow to amount * (1 + interest_rate) and in two years, the amount grows to amount * (1 + interest_rate) * (1 + interest_rate) assuming annual compounding of your interest rate. Your inclusion of time, and the continuous multiplication by amount are errors. Note that there is a closed form solution. For rate r, initial amount I, final amount A, the number of years t is t = ln(A / I) / ln(1 + r) which you need to round up.
Calculation not returning correct value
I was asked to write this program: "A software company sells a package that retails for $99. Quantity discounts are given according to the following table: QUANTITY DISCOUNT 10-19 20% 20-49 30% 50-99 40% 100 or more 50% Write a program that asks for the number of units sold and computes the total cost of the purchase. Input Validation: Make sure the number of units is greater than 0" This is what I have so far: #include <iostream> #include <string> //String class- a string of text #include <iomanip> //Required for setw= the field width of the value after it using namespace std; int main() { double sales, charges, numOfUnits = 0, rateA = .20, rateB = .30, rateC = .40, rateD = .50; //Set the numeric output formatting: cout << fixed << showpoint << setprecision(2); cout << "Enter the quantity for your order: "; cin >> sales; // Determine the discount: double PRICE=99.0; if (sales >= numOfUnits) if (sales >= 10 && sales <= 19 ) rateA; charges = PRICE - rateA *sales; if (sales >= 20 && sales <= 49) rateB; charges = PRICE - rateB *sales; if (sales >= 50 && sales <= 99) rateC; charges = PRICE - rateC *sales; if (sales > 100 ) rateD; charges = PRICE - rateD *sales; cout << "Your total price for this quantity is: $" <<charges << " per unit."<< endl; cout << "That is an invalid number. Run the program again\n " << "and enter a number greater than\n" << numOfUnits << ".\n"; } After compiling, the output does not give me the right answers. Maybe my math is wrong, or my flow is off? any suggestions? I do not want anyone to write this for me, but maybe give me some pointers
You need to use braces {} around multi-line conditions if (sales >= 10 && sales <= 19 ) rateA; charges = PRICE - rateA *sales; is actually if (sales >= 10 && sales <= 19 ) rateA; charges = PRICE - rateA *sales; i.e. rateA is executed conditionally and the update to charges is always executed. Also, statements like rateA; have no effect so should either be updated or removed.
This sort of construct: if (sales >= 50 && sales <= 99) rateC; charges = PRICE - rateC *sales; does: if (sales >= 50 && sales <= 99) rateC; charges = PRICE - rateC *sales; In other words, charges is always calculated with rateC, rather than only being so when the sales is in the relevant range. rateC inside the if-statement is also completely useless - it doesn't "do" anything with rateC, the it's just telling the compiler to "go look at this value, then throw it away" [which the compiler probably translates to "do nothing at all", because "looking" at rateC doesn't actually have any visible effect outside of that statement, so it can be removed].
On a quick glance, I think the math is off a bit. It should be : double originalPrice = PRICE * sales; if (sales >= 10 && sales <= 19 ) charges = originalPrice - (rateA * originalPrice); else if (sales >= 20 && sales <= 49) and so on..
Loan calculator alteration
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?