how to print grand total from an array inside the main - c++

#include<iostream>
#include<string>
#include<iomanip>
using namespace std;
struct EmployeeData
{
string employeeName;
float overtime;
float grossPay;
float hoursWorked;
float hourlyRate;
float statetaxOwed;
float statetaxRate;
float fedtaxOwed;
float fedtaxRate;
float netPay;
float totalgp;
float totalft;
float totalst;
float totalnp;
};
EmployeeData employee[4]; //array of 4 employees
void calculate_stats(EmployeeData& employee);
int main()
{
for (int i = 0; i < 4; ++i)
{
cout << "Please enter Employee #" << (i+1) << "'s" << " name: ";
cin.ignore();
getline(cin, employee[i].employeeName);
cout << "Please enter Employee #" << (i+1) << "'s hours worked: ";
cin >> employee[i].hoursWorked;
cout << "Please enter Employee #" << (i+1) << "'s hourly rate: ";
cin >> employee[i].hourlyRate;
cout << "Please enter Employee #" << (i+1) << "'s Federal Tax Rate: ";
cin >> employee[i].fedtaxRate;
cout << "Please enter Employee #" << (i+1) << "'s State Tax Rate: ";
cin >> employee[i].statetaxRate;
cout << endl;
}
for (int i = 0; i < 4; ++i)
{
calculate_stats(employee[i]);
cout << setprecision(2) << showpoint << fixed;
cout << "Employee #" << (i+1) << "'s name is: " << employee[i].employeeName << endl;
cout << "Employee #" << (i+1) << "'s Gross Pay is: $" << employee[i].grossPay << endl;
cout << "Employee #" << (i+1) << "'s Federal Taxes owed is: $" << employee[i].fedtaxOwed << endl;
cout << "Employee #" << (i+1) << "'s State Taxes owed is: $" << employee[i].statetaxOwed << endl;
cout << "Employee #" << (i+1) << "'s Net Pay is: $" << employee[i].netPay << endl;
cout << endl;
}
cout << "Total Gross Pay: " << employee[4].totalgp << endl; //here is the problem
cout << "Total Federal Tax Owed: " << employee[4].totalft<< endl;
cout << "Total State Tax Owed: " << employee[4].totalft<< endl;
cout << "Total Net Pay: " << employee[4].totalft << endl;
}
void calculate_stats(EmployeeData& employee)
{
if (employee.hoursWorked>40) {
employee.hoursWorked = ((employee.hoursWorked-40) * (1.5)) + 40;
}
else {
employee.hoursWorked = employee.hoursWorked;
}
employee.grossPay = employee.hoursWorked * employee.hourlyRate;
employee.fedtaxOwed = employee.grossPay * (employee.fedtaxRate/100);
employee.statetaxOwed = employee.grossPay * (employee.statetaxRate/100);
employee.netPay = (employee.grossPay - employee.fedtaxOwed- employee.statetaxOwed);
employee.totalgp = employee.totalgp + employee.grossPay;
employee.totalft = employee.totalft + employee.fedtaxOwed;
employee.totalst = employee.totalst + employee.statetaxOwed;
employee.totalnp = employee.totalnp + employee.netPay;
}
I was sure to include that cout block outside of the for-loops but still in the main. Using calculate stats did not change the output for me. The output is giving me all 0.00...they should be complete totals across all 4 Employees (so if the gross pay for all 4 employees is 1000, then the total gross pay should be 4000, which is a grand total which I accounted for in my calculations: employee.totalgp = employee.totalgp + employee.grossPay;. Here is what the output looks like (a snapshot of the wrong display, the rest works fine)...
Total Gross Pay: 0.00
Total Federal Tax Owed: 0.00
Total State Tax Owed: 0.00
Total Net Pay: 0.00
Press any key to continue . . .
How do I fix this? Thank you!

The values are printing out as zero mainly due to luck on your part. Your array, defined as EmployeeData employee[4] allows for access to employee[0] to employee[3]. Accessing employee[4] for your print is accessing memory beyond what was allocated for your array.
Beyond that, you store nothing at the memory location with your code, which is not such a bad thing. You do store each set of data twice in each record:
employee.totalgp = employee.totalgp + employee.grossPay;
employee.totalft = employee.totalft + employee.fedtaxOwed;
employee.totalst = employee.totalst + employee.statetaxOwed;
employee.totalnp = employee.totalnp + employee.netPay;
Each call to calculate_stats is storing the global values in different locations, defeating your attempt to have a cumulative count. You need to define a separate EmployeeData instance to store the accumulated totals, and write the values into that object.
Once you have a new structure in place to store your totals, change the above four lines in your existing calculate_stats method to update the global totals structure.

Related

expected 'while' or expected '}' Answered before yes, but I can't fix it myself

I have already checked all the other questions but I just can't fix it.. I am a nuub at coding.
I don't know why it says it needs a while or where to put it, and it gives the wrong answer for the LOCS function also is there anything i can do about the default pointer warning. this is just a start i will be extending this later so it would be a big help and i have tried while and closing brackets everywhere lol
Btw if anyone can tell me how I can use the input as decision as you can see I am using 1 and 2, but If I could use permanent and casual that would be great.
// Calculate an employee's weekly salary
// Use a do while loop, and an if else statement to have user input data and display the correct values
#include <iostream>
using namespace std;
void main()
{
//Declaring the constant variables
const double BONUS_RATE = 5.0;
//Declaring the variables
int hours;
int sales;
int Status;
string permanent, casual, Name, status, result, employee;
double rate, sale_bonus, netPay, gross;
//set decimal point to 2 positions
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
//Display name
cout << "Calculate an employee's weekly salary\n\n";
//Do while loop to get hourly rate
do {
cout << "Enter employee name: ";
cin >> Name;
cout << "Please enter 1 if employee is permanent or 2 if casual: ";
cin >> Status;
Status = 0;
while (Status < 1 || Status > 2);
if (Status = 1)
{
cout << "Permanent employees have a fixed salary of $1000 per week" << endl;
sales = 0;
(sales < 1 || sales > 10);
cout << "If any please enter how many sales employee made this week:";
cin >> sales;
sale_bonus = sales * BONUS_RATE;
netPay = 1000 + sale_bonus;
cout << endl;
cout
<< "Hours Worked: \t" << hours << endl
<< "Gross Pay: \t" << gross << endl
<< "Net Pay \t" << netPay << endl;
}
else if (Status = 2) {
cout << "Casual employee's hourly rate is $15";
rate = 15.00;
cout << endl;
//while loop for hours
hours = 0;
while (hours < 1 || hours > 60)
{
cout << "Please enter how many hours you have worked this week:" << endl;
cout << "Minimum hours is 1" << endl;
cout << "Maximum hours are 60" << endl;
cout << "Enter hours worked: ";
cin >> hours;
}
//while loop for bonus
sales = 0;
while (sales < 1 || sales > 10)
{
cout << "Please enter how many sales you made this week:";
cin >> sales;
}
//Calculate pay
gross = hours * rate;
sale_bonus = sales * BONUS_RATE;
netPay = gross + sale_bonus;
//Display the results
cout << endl
<< "Hourly Rate: \t" << rate << endl
<< "Hours Worked: \t" << hours << endl
<< "Gross Pay: \t" << gross << endl
<< "Net Pay \t" << netPay << endl;
}
}
}
#include <iostream>
using namespace std;
void main()
{
//Declaring the constant variables
const double BONUS_RATE = 5.0;
//Declaring the variables
int hours;
int sales;
int Status;
string permanent, casual, Name, status, result, employee;
double rate, sale_bonus, netPay, gross;
//set decimal point to 2 positions
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
//Display name
cout << "Calculate an employee's weekly salary\n\n";
//Do while loop to get hourly rate
do {
cout << "Enter employee name: ";
cin >> Name;
cout << "Please enter 1 if employee is permanent or 2 if casual: ";
cin >> Status;
} while (Status < 1 || Status > 2); // add while after do block with }
if (Status == 1)// use '==' equality check not '=' .
{
cout << "Permanent employees have a fixed salary of $1000 per week" << endl;
sales = 0;
(sales < 1 || sales > 10);
cout << "If any please enter how many sales employee made this week:";
cin >> sales;
sale_bonus = sales * BONUS_RATE;
netPay = 1000 + sale_bonus;
cout << endl;
cout
<< "Hours Worked: \t" << hours << endl
<< "Gross Pay: \t" << gross << endl
<< "Net Pay \t" << netPay << endl;
}
else if (Status == 2) { // use '==' equality check not '=' .
cout << "Casual employee's hourly rate is $15";
rate = 15.00;
cout << endl;
//while loop for hours
hours = 0;
while (hours < 1 || hours > 60)
{
cout << "Please enter how many hours you have worked this week:" << endl;
cout << "Minimum hours is 1" << endl;
cout << "Maximum hours are 60" << endl;
cout << "Enter hours worked: ";
cin >> hours;
}
//while loop for bonus
sales = 0;
while (sales < 1 || sales > 10)
{
cout << "Please enter how many sales you made this week:";
cin >> sales;
}
//Calculate pay
gross = hours * rate;
sale_bonus = sales * BONUS_RATE;
netPay = gross + sale_bonus;
//Display the results
cout << endl
<< "Hourly Rate: \t" << rate << endl
<< "Hours Worked: \t" << hours << endl
<< "Gross Pay: \t" << gross << endl
<< "Net Pay \t" << netPay << endl;
}
}
I have made the suitable changes :
Use == to check equality instead of = operator!
Syntax of do while : do { //code... } while(condition).
The while must follow the do after closing the block!
Your Mistake
the main mistake is you have not close the do while loop, ask in comment for more clarification!
PS. I recommend you first copy my code and then run, and then analyse the issue!
Use this code this will work
#include
using namespace std;
void main()
{
//Declaring the constant variables
const double BONUS_RATE = 5.0;
//Declaring the variables
int hours;
int sales;
int Status;
string permanent, casual, Name, status, result, employee;
double rate, sale_bonus, netPay, gross;
//set decimal point to 2 positions
cout.setf(ios::fixed);
cout.setf(ios::showpoint);
cout.precision(2);
//Display name
cout << "Calculate an employee's weekly salary\n\n";
//Do while loop to get hourly rate
while(1){
cout << "Enter employee name: ";
cin >> Name;
cout << "Please enter 1 if employee is permanent or 2 if casual: ";
cin >> Status;
Status = 0;
while (Status < 1 || Status > 2);
if (Status = 1)
{
cout << "Permanent employees have a fixed salary of $1000 per week" << endl;
sales = 0;
(sales < 1 || sales > 10);
cout << "If any please enter how many sales employee made this week:";
cin >> sales;
sale_bonus = sales * BONUS_RATE;
netPay = 1000 + sale_bonus;
cout << endl;
cout
<< "Hours Worked: \t" << hours << endl
<< "Gross Pay: \t" << gross << endl
<< "Net Pay \t" << netPay << endl;
}
else if (Status = 2) {
cout << "Casual employee's hourly rate is $15";
rate = 15.00;
cout << endl;
//while loop for hours
hours = 0;
while (hours < 1 || hours > 60)
{
cout << "Please enter how many hours you have worked this week:" << endl;
cout << "Minimum hours is 1" << endl;
cout << "Maximum hours are 60" << endl;
cout << "Enter hours worked: ";
cin >> hours;
}
//while loop for bonus
sales = 0;
while (sales < 1 || sales > 10)
{
cout << "Please enter how many sales you made this week:";
cin >> sales;
}
//Calculate pay
gross = hours * rate;
sale_bonus = sales * BONUS_RATE;
netPay = gross + sale_bonus;
//Display the results
cout << endl
<< "Hourly Rate: \t" << rate << endl
<< "Hours Worked: \t" << hours << endl
<< "Gross Pay: \t" << gross << endl
<< "Net Pay \t" << netPay << endl;
}
}
}

How do I get the month to stop displaying 1.00, 2.00, ... etc

I'm fairly new to c++ and I am writing a program that calculates the balance of a savings account at the end of a three-month period. I am supposed to use loops, which I have done and don't have much of a problem. The problem I am having is that all the numbers for deposit, withdrawal, current balance, etc. are supposed to be displayed as x.xx, and I am getting that output, but it also does that for the month. How do I make it so that the month doesn't display as x.xx?
Here's my code:
#include "pch.h"
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
double startbalance;
double annualrate;
double monthlyrate;
double deposit;
double withdrawal;
double totaldeposit = 0;
double totalwithdrawal = 0;
double totalinterest = 0;
double monthstart = 0;
double monthend = 0;
printf("Welcome to Your Bank!\n");
cout << "What is your starting Balance? $";
cin >> startbalance;
cout << "What is the annual interest rate?. Please enter whole value. For example 6 for 6% :";
cin >> annualrate;
monthend += startbalance;
for (double month = 1; month <= 3; month++)
{
cout << "Month #" << month << endl;
do
{
cout << setprecision(2) << fixed;
cout << "Current Balance: $" << monthend << endl;
cout << "Please enter total amount of deposits: $";
cin >> deposit;
if (deposit < 0)
{
cout << "Deposit must be a positive number!\n";
}
} while (deposit < 0);
totaldeposit += deposit;
monthend += deposit;
do
{
cout << "Please enter total amount of withdrawals: $";
cin >> withdrawal;
if (withdrawal < 0 || withdrawal > monthend)
{
cout << "Withdrawal must be a positive number and not be larger than balance: $" << monthend << endl;
}
} while (withdrawal < 0 || withdrawal > totaldeposit);
cout << endl;
totalwithdrawal += withdrawal;
monthend -= withdrawal;
monthlyrate = ((monthstart + monthend) / 2 * (annualrate / 12));
totalinterest += monthlyrate;
cout << "New Balance: $" << monthend << "\n";
}
cout << endl;
cout << fixed << showpoint << setprecision(2);
cout << "Start Balance: " << setw(9) << "$" << startbalance << "\n";
cout << "Total Deposits: " << setw(9) << "$" << totaldeposit << "\n";
cout << "Total Withdrawals: " << setw(9) << "$" << totalwithdrawal << "\n";
cout << "Total Interest Earned: " << setw(9) << "$" << totalinterest << "\n";
cout << "Final balance: " << setw(9) << "$" << monthend << "\n";
return 0;
}
Just type-cast your month variable to int before displaying.
cout << "Month #" << (int)month << endl;
That should fix your issue.
You can make monthend an int or a long. .........
Please make Data Type of your month as int instead of double.
double is a floating point data type. int is a whole number like 1, 2, 3, 4 and so on. Double is numbers with decimals like 1.1 or 45.564, float is a even more specific version of double
Example:
//if you just going to work with whole numbers
int a;
a = 1
//if you're working with numbers with a bit more precision
float b;
b = 1.1234
//if you're working with numbers with massive precision..
double c;
c = 1.123456
Your variable types seem to be fine for the calculation; I believe your problem is within this statement:
for (double month = 1; month <= 3; month++) {
cout << "Month #" << month << endl;
it is within your loop as why your month is printing out: 1.0, 2.0 etc.
change it to this:
for ( int month = 1; month <=3; month++ ) {
cout << "Month #" << month << endl;
Logically, variable month should be an integer.
Declare its datatype as int instead of double.

Uninitialized local variable used?

having some problems with a class exercise
#include <iostream>
#include <string>
using namespace std;
int main()
{
int employeeNumber, grossPay, stateTax, federalTax, ficaHold;
int totalGross, totalState, totalFederal, totalFica, totalPay = 0;
do // do-while loop for employee number
{
cout << "Enter the employee number: " << endl;
cout << "(Enter 0 to quit.)" << endl;
cin >> employeeNumber;
} while (employeeNumber < 0);
while (employeeNumber != 0)
{
do // gross pay greater than state tax + federal tax + FICA
{
do // entry and validation for gross pay
{
cout << "How much gross pay ? ";
cin >> grossPay;
} while (grossPay < 0);
do //entry and validation for state tax
{
cout << "How much state tax ? ";
cin >> stateTax;
} while (stateTax < 0 || stateTax > grossPay);
do // entry and validation federal tax
{
cout << "How much federal tax ? ";
cin >> federalTax;
} while (federalTax < 0 || federalTax > grossPay);
do // entry and validation for FICA holdings amount
{
cout << "How much FICA withholdings ? ";
cin >> ficaHold;
} while (ficaHold < 0 || ficaHold > grossPay);
if (grossPay < stateTax + federalTax + ficaHold) // Message to verify taxes are not greater than pay
cout << "State tax, federal tax, and FICA holdings cannot be greater than gross pay. Please re-enter these values." << endl;
} while (grossPay < stateTax + federalTax + ficaHold);
totalGross += grossPay;
totalState += stateTax;
totalFederal += federalTax;
totalFica += ficaHold;
totalPay = totalGross - (totalState + totalFederal + totalFica);
do // do-while loop for employee number
{
cout << "Enter the employee number: " << endl;
cout << "(Enter 0 to quit.)" << endl;
cin >> employeeNumber;
} while (employeeNumber < 0);
}
cout << endl << endl << "The total gross pay is: $" << totalGross << endl;
cout << "The total state tax is :" << totalState << endl;
cout << "The total federal tax :" << totalFederal << endl;
cout << "The total FICA withholdings :" << totalFica << endl;
cout << "Net pay :" << totalPay << endl << endl;
return 0;
}
getting some errors for the variables on lines 95-98, eg "uninitialized local variable 'totalState'" and not really sure what to do, i already gave those variables value in the declaration before any loops, and im not sure if i can move them before anything while keeping the goal of the program
The first time you use totalState, you're both reading and writing: totalState += stateTax;. The problem is that you've never initialized totalState, so there's no guarantee what the value will be when you try to read it.
For the record, you have other uninitialized variables as well: totalGross, totalFederal, and totalFica.

Math results in zero. New to coding

I'm trying to complete an assignment but I'm having difficulty with the math expressions and variables in general. I'm trying to make a program that takes user info on groceries and then outputs a receipt. Here is my code.
#include <iostream>
#include <string>
using namespace std;
int main()
{
//user input
string firstItem, secondItem;
float firstPrice, secondPrice;
int firstCount, secondCount;
double salesTax = 0.08675;
double firstExt = firstPrice * firstCount;
double secondExt = secondPrice * secondCount;
double subTotal = firstExt + secondExt;
double tax = subTotal * salesTax;
double total = tax + subTotal;
//user input
cout << "What is the first item you are buying?" << endl;
getline(cin, firstItem);
cout << "What is the price of the " << firstItem << "?" << endl;
cin >> firstPrice;
cout << "How many " << firstItem << "s?" <<endl;
cin >> firstCount;
cin.ignore();
cout << "What is the second item you are buying?" << endl;
getline(cin, secondItem);
cout << "what is the price of the " << secondItem << "?" << endl;
cin >> secondPrice;
cout << "How many " << secondItem << "s?" << endl;
cin >> secondCount;
// receipt output
cout << "1st extended price: " << firstExt << endl;
cout << "2nd extended price: " << secondExt << endl;
cout << "subtotal: " << subTotal << endl;
cout << "tax: " << tax << endl;
cout << "total: " << total << endl;
return 0;
}
The program output either 0 for all or negatives.
Your calculations must go after you read in the values, not before. You're making your calculations based on uninitialized variables.
A declaration and initialisation like
double firstExt = firstPrice * firstCount;
initialises firstExt to be the product of the current values AT THAT POINT of firstPrice and firstCount.
It doesn't set up some magic so that the value of firstExt is recalculated whenever the values of firstPrice or firstCount are changed.
In your case, firstPrice and firstCount are uninitialised variables when you do this. Accessing values of uninitialised variables of type int gives undefined behaviour.
What you need to do is something like
cout << "What is the price of the " << firstItem << "?" << endl;
cin >> firstPrice;
cout << "How many " << firstItem << "s?" <<endl;
cin >> firstCount;
firstExt = firstPrice*firstCount; // do the calculation here
If the value of firstExt is not needed until this point, you can declare it here instead;
double firstExt = firstPrice*firstCount; // do the calculation here
which means any earlier use of firstExt will give a compiler diagnostic.

Loan repayments calculation in C++

I'm writing a program which will calculate monthly payments for a loan. It is not giving the correct answer though. Here is my code:
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
double YearlyInt, LoanAmount, Payment, AmountPaid, MonthlyInt;
int NumPayments;
cout << "Enter the loan amount (LoanAmount) --> ";
cin >> LoanAmount;
cout << "Enter the YEARLY interest rate as a percentage --> ";
cin >> YearlyInt;
cout << "Enter number of payments --> ";
cin >> NumPayments;
cout << "Loan amount: " << LoanAmount << endl;
cout << "Yearly Interest Rate: " << YearlyInt << "%" << endl;
cout << "Number of Payments: " << NumPayments << endl;
MonthlyInt = YearlyInt / 12;
Payment = MonthlyInt * pow (( 1 + MonthlyInt ), NumPayments) / (pow(( 1 + MonthlyInt), NumPayments) -1) * LoanAmount;
cout << "Monthly Payment: " << Payment << endl;
AmountPaid = Payment * 36;
cout << "Amount Paid Back: " << AmountPaid << endl;
cout << "Interest Paid: " << (AmountPaid - LoanAmount) << endl;
cout << "Program Over" << endl << endl << endl << endl;
cout << "Press Enter to end -->" << endl;
return 0;
}
The program uses this formula:
MonthlyInt * pow(1 + MonthlyInt, NumPayments) * LoanAmount
Payment = ---------------------------------------------------------------
pow(1 + MonthlyInt, NumPayments) - 1
This is what I get as an output:
Enter the loan amount (LoanAmount) --> 10000
Enter the YEARLY interest rate as a percentage --> 12
Enter number of payments --> 36
Loan amount: 10000
Yearly Interest Rate: 12%
Number of Payments: 36
Monthly Payment: 10000
Amount Paid Back: 360000
Interest Paid: 350000
Program Over
Press Enter to end -->
Press any key to continue . . .
As you can see, the Loan amount is clearly wrong. How can I fix my code?
Step 1: MonthlyInt does NOT equal YearlyInt / 12 because of the effect of compounding interest. The general formula for converting between rate of a smaller period and the equivalent rate of a larger period is: (1 + r) ^n = 1 + R. So in this case r = MonthlyInt and R = YearlyInt. Therefore, the first order of business is to change
from:
MonthlyInt = YearlyInt / 12;
to:
MonthlyInt = pow ( (1.0 + YearlyInt) , (1.0/NumPayments) ) - 1.0; // note decimals!
Step 2: Add a line that prints MonthlyInt so that you can verify the calculation. :)
Step 3: Change AmountPaid = Payment * 36; to AmountPaid = Payment * NumPayments;
Step 4: Optionally, add dollar signs and clean up the decimals.
We must add the header #include<iomanip>, then set the number of decimals with cout << setprecision(n) << fixed << whateverVariable, where n equals the number of decimal places you want.
Revised code:
#include<iostream>
#include<cmath>
#include<iomanip>
using namespace std;
int main()
{
double YearlyInt = -1, LoanAmount = -1, Payment = -1, AmountPaid = -1, MonthlyInt = -1;
int NumPayments;
cout << "Enter the loan amount (LoanAmount) --> ";
cin >> LoanAmount;
cout << "Enter the YEARLY interest rate as a decimal number (e.g. 3.25% as .0325) --> ";
cin >> YearlyInt;
cout << "Enter number of payments --> ";
cin >> NumPayments;
cout << "Loan amount: $" << setprecision(2) << fixed << LoanAmount << endl;
cout << "Yearly Interest Rate: " << setprecision(3) << YearlyInt * 100 << "%" << endl;
cout << "Number of Payments: " << NumPayments << endl;
MonthlyInt = pow ( (1.0 + YearlyInt) , (1.0/NumPayments) ) - 1.0;
cout << "MonthlyInt: " << MonthlyInt*100 << "%" << endl;
Payment = MonthlyInt * pow (( 1 + MonthlyInt ), NumPayments) / (pow(( 1 + MonthlyInt), NumPayments) -1) * LoanAmount;
cout << "Monthly Payment: $" << setprecision(2) << Payment << endl;
AmountPaid = Payment * NumPayments;
cout << "Amount Paid Back: $" << AmountPaid << endl;
cout << "Interest Paid: $" << (AmountPaid - LoanAmount) << endl;
cout << "Program Over" << endl << endl << endl << endl;
cout << "Press Enter to end -->" << endl;
return 0;
}
Assumptions: the loan has a no-fees APR of YearlyInt to be compounded monthly, with monthly payments, with the first payment applied on the last day of the same month in which the loan is originated, and with all “on time” payments (whatever that is defined as, by the lendor) being applied as if paid on the last day of the applicable period.
There are a few problems:
You enter rate in percents, so convert them to a decimal number: MonthlyInt/100.0
Your number of payments should be either fixed, or entered by user. Now it is firstly read in, but then there is 36 used in the code. It should be replaced with the proper variable.
Be careful with integer division. There is no mistake at the moment, but to avoid such, use 1.0 and 100.0 instead of just 1 and 100 if you want to be sure you have floats.
Be sure your math is right. In fact, this should be the very first thing you do. This is a programming site though, so it's off-topic here.
(optional) Conventionally, variable names shouldn't start with capital letter.
Here is a program which correctly calculates the payments assuming the following:
Yearly interest is calculated as compounded monthly interest.
There are no fees applied to the loan.
The repayments start one month after the loan is given.
The monthly payment amounts do not change.
No monthly payments are missed.
.
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
double YearlyInt, LoanAmount, Payment, AmountPaid, MonthlyInt;
int NumPayments;
cout << "Enter the loan amount (LoanAmount) --> ";
cin >> LoanAmount;
cout << "Enter the YEARLY interest rate as a percentage --> ";
cin >> YearlyInt;
cout << "Enter number of monthly payments --> ";
cin >> NumPayments;
cout << "Loan amount: " << LoanAmount << endl;
cout << "Yearly Interest Rate: " << YearlyInt << "%" << endl;
cout << "Number of Monthly Payments: " << NumPayments << endl;
MonthlyInt = pow( 1 + YearlyInt/100, 1.0/12 );
Payment = LoanAmount * pow( MonthlyInt, NumPayments ) *
( MonthlyInt - 1 ) /
( pow( MonthlyInt, NumPayments ) - 1 );
cout << "Monthly Payment: " << Payment << endl;
AmountPaid = Payment * NumPayments;
cout << "Amount Paid Back: " << AmountPaid << endl;
cout << "Interest Paid: " << (AmountPaid - LoanAmount) << endl;
cout << "Program Over" << endl << endl << endl << endl;
return 0;
}
Is the program supposed to calculate compound interest or simple interest?
Your calculation appears to be incorrect. You calculate a monthly interest rate, which makes it look like simple interest, but you use pow, which indicates something to do with compound interest. You should probably look into that.
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
double YearlyInt, LoanAmount, Payment, AmountPaid, MonthlyInt, NumPayments;
cout << "Enter the loan amount (LoanAmount) --> ";
cin >> LoanAmount;
cout << "Enter the YEARLY interest rate as a percentage --> ";
cin >> YearlyInt;
cout << "Enter number of payments --> ";
cin >> NumPayments;
cout << "Loan amount: " << LoanAmount << endl;
cout << "Yearly Interest Rate: " << YearlyInt << "%" << endl;
cout << "Number of Payments: " << NumPayments << endl;
MonthlyInt = (YearlyInt/100.0) / 12;
Payment = MonthlyInt * pow (( 1 + MonthlyInt ), NumPayments) / (pow(( 1 + MonthlyInt), NumPayments) -1) * LoanAmount;
cout << "Monthly Payment: " << Payment << endl;
AmountPaid = Payment * 36;
cout << "Amount Paid Back: " << AmountPaid << endl;
cout << "Interest Paid: " << (AmountPaid - LoanAmount) << endl;
cout << "Program Over" << endl << endl << endl << endl;
cout << "Press Enter to end -->" << endl;
return 0;
Got it simply switched MonthlyInt = YearlyInt / 12; to MonthlyInt = (YearlyInt/100.0) / 12;
#include<iostream>
#include<cmath>
using namespace std;
int main()
{
double YearlyInt, LoanAmount, Payment, AmountPaid, MonthlyInt, NumPayments;
cout << "Enter the loan amount (LoanAmount) --> ";
cin >> LoanAmount;
cout << "Enter the YEARLY interest rate as a percentage --> ";
cin >> YearlyInt;
cout << "Enter number of payments --> ";
cin >> NumPayments;
cout << "Loan amount: " << LoanAmount << endl;
cout << "Yearly Interest Rate: " << YearlyInt << "%" << endl;
cout << "Number of Payments: " << NumPayments << endl;
MonthlyInt = (YearlyInt/100.0) / 12;
Payment = MonthlyInt * pow (( 1 + MonthlyInt ), NumPayments) / (pow(( 1 + MonthlyInt), NumPayments) -1) * LoanAmount;
cout << "Monthly Payment: " << Payment << endl;
//correction to Amount paid Value
AmountPaid = Payment * NumPayments;
cout << "Amount Paid Back: " << AmountPaid << endl;
cout << "Interest Paid: " << (AmountPaid - LoanAmount) << endl;
cout << "Program Over" << endl << endl << endl << endl;
cout << "Press Enter to end -->" << endl;
return 0;
}
In case you don't want to use pow functions, you can directly calculate the geometric sum and nth term of the series yourself (the pow() comes from geometric terms and sum). See the proof here: https://mortgagecalculator.mes.fm/amortization-formula-proof
int months = 60;
float principle = 10000;
float rate = 6.5f/100;
float monthly_factor = 1 + rate / 12;
float temp = 1, temp2= monthly_factor;
for(int i = 0;i < months - 1; i++){ //this for loop calculates the geometric sum with ratio of monthly_factor in temp and pow(monthly_factor,n) in temp2
temp *= monthly_factor;
temp2 *= monthly_factor;
temp += 1;
}
float monthly_payment = principle * temp2 / temp;