C++: interestEarned coming back wrong - c++

I'm learning C++ and this is an assignment I have to do, it's complete but my interestEarned is not coming back correctly but the bankBalance is correct so I'm just not displaying interestEarned correctly. "Total Interest Earned: $65.50" is incorrect is supposed to display "$120.50" as my teacher said. What am I doing wrong?
Here is my code:
#include <iostream>
#include <iomanip>
using namespace std;
int main() {
// Variables
int numOfCustomers, numOfMonths = 0;
double bankBalance, depositAmount, withdrawnAmount, interestRate, interestEarned = 0.0;
const int MIN = 0;
// Asking for Number of Customers
cout << "Enter the number of customers: ";
cin >> numOfCustomers;
// Making sure the input was not 0 or lower
while (numOfCustomers <= MIN) {
cout << "==>Number of customers must be at least 1. Try again: ";
cin >> numOfCustomers;
}
// Validating each Customer
for (int c = 1; c < (numOfCustomers + 1); c++) {
// Start of each Customer
cout << "\nCUSTOMER " << c << ":\n";
// Asking for Number of Months --
cout << "Enter the number of months the account has been opened: ";
cin >> numOfMonths;
// Making sure the input was not 0 or lower
while (numOfMonths <= MIN) {
cout << "==>Number of months must be at least 1. Try again: ";
cin >> numOfMonths;
}
// Asking for Starting Balance --
cout << "Enter the starting balance: $";
cin >> bankBalance;
// Making sure the input was not 0 or lower
while (bankBalance < MIN) {
cout << "==>Starting balance can't be negative. Try again: $";
cin >> bankBalance;
}
// Asking for Monthly Interest Rate --
cout << "Enter the monthly interest rate as a decimal (i.e. 0.05 = 5%): ";
cin >> interestRate;
// Making sure the input was not 0 or lower
while (interestRate < MIN) {
cout << "==>Monthly interest rate can't be a nagative. Try again: ";
cin >> interestRate;
}
// Validating each Month
for (int m = 1; m < (numOfMonths + 1); m++) {
// Deposit Amount
cout << "\nEnter deposit amount for Month " << m << ": $";
cin >> depositAmount;
bankBalance = bankBalance + depositAmount;
// Withdrawn Amount
cout << "Enter withdrawn amount for Month " << m << ": $";
cin >> withdrawnAmount;
bankBalance = bankBalance - withdrawnAmount;
// Calculating Interest Earned
interestEarned = bankBalance * interestRate;
// Complete bankBalance
bankBalance = bankBalance + interestEarned;
}
// Account Summary
cout << "\nACCOUNT SUMMARY" << endl;
cout << fixed << setprecision(2);
cout << "Number Months Active: " << numOfMonths << endl;
cout << "Ending Balance: $" << bankBalance << endl;
cout << "Total Interest Earned: $" << interestEarned << endl;
}
system("pause");
return 0;
}

Use another variable that is initialized to zero before the loop. In the loop, add the value of interestEarned to it. - #Peter

Related

Having some trouble with a assignment in c++

I have a assignment I've been working on and my code is working but the results are off by a hair. I know the issue has to do with rounding but I just can't seem to figure out where the issue lies. I've included the assignment details as well as the results i'm getting versus the expected result. Any help is appreciated.
Link for images https://imgur.com/a/bqIcxfT
'''
// This program will display the size of a population for given number of years
// taking into account annual birth and death rates as well as the number of
// people who move away and move into the area.
#include <iostream>
#include <iomanip>
using namespace std;
//Function prototype
double calculatePop (double, double, double, int, int);
int main ()
{
double P; // Starting population
double B; // Annual birth rate
double D; // Annual death rate
int A; // Average number of people who arrive
int M; // Average number of people who move away
int nYears; // The number of years to display
cout << "This program calculates population change." << endl;
// Set numeric formatting
cout << setprecision(0) << fixed;
// Get starting population size
cout << "Enter the starting population size: ";
cin >> P;
while (P<2){
cout << "Starting population must be 2 or more.";
cout << "Please re-enter:";
cin >> P;}
// Get the annual birth rate
cout << "Enter the annual birth rate (as % of current population): ";
cin >> B;
while (B<0){
cout << "Birth rate percent cannot be negative.";
cout << "Please re-enter:";
cin >> B;}
B/=100;
// Get annual death rate
cout << "Enter the annual death rate (as % of current population): ";
cin >> D;
while (D<0){
cout << "Death rate percent cannot be negative.";
cout << "Please re-enter:";
cin >> D;}
D/=100;
// Get number of people who arrive
cout << "How many individuals move into the area each year? ";
cin >> A;
while (A<0){
cout << "Arrivals cannot be negative.";
cout << "Please re-enter:";
cin >> A;}
// Get number of people who move away
cout << "How many individuals leave the area each year? ";
cin >> M;
while (M<0){
cout << "Departures cannot be negative.";
cout << "Please re-enter:";
cin >> M;}
// Get number of years to see data for
cout << "For how many years do you wish to view population changes? " << endl << endl;
cin >> nYears;
while (nYears<1){
cout << "Years must be one or more.";
cout << "Please re-enter:";
cin >> nYears;}
cout << "Starting population: " << P << endl << endl;
//Display the population to user
for (int y=1; y<=nYears; y++)
{
P = calculatePop(P, B, D, A, M);
cout << "Population at the end of year " << y << " is " << P << ".\n";
}
}
double calculatePop (double P, double B, double D, int A, int M)
{
double N; //New Population Size
N = P + (B*P) - (D*P) + A - M;
return N;
}
'''
The value is correctly calculated but not outputted the same way as in the assignment. Setting setprecision(0) along with fixed will round the number to the nearest integer while the result shown in the assignment is the truncated number. To truncate the result, use
cout << "Population at the end of year " << y << " is " << int(P) << ".\n";

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.

How can I get user input to exit a loop?

I have a problem with my code, every time I loop it with the answer 'y'(Yes) it loops to infinity?
I'm trying to make a loan calculator and every time the user is done calculating with a transaction and wants to reset, and do another calculation if he enters in a value 'y', and if he enters 'n' the program will end.
Here's my code so far:
#include <iostream>
#include <string>
#include <iomanip>
#include <cmath>
using namespace std;
int main() {
char ans = 'y';
do {
string name;
int Months;
int n;
double LoanAmount, Rate, MonthlyInterest, TotalLoanAmount, MonthlyAmortization, OutstandingBalance;
cout << fixed << showpoint;
cout << "Enter Name of Borrower: ";
getline(cin, name);
cout << "Enter Loan Amount: ";
cin >> LoanAmount;
cout << "Enter Number of Months to Pay: ";
cin >> Months;
cout << "Enter Interest Rate in Percent(%): ";
cin >> Rate;
cout << setprecision(2);
MonthlyInterest = LoanAmount * Rate;
TotalLoanAmount = LoanAmount + (MonthlyInterest * Months);
cout << "Monthly Interest: " << MonthlyInterest << endl
<< "Total Loan Amount with interest: " << TotalLoanAmount << endl;
cout << setw(100)
<< "\n\tSUMMARY OF OUTSTANDING INSTALLMENT" << endl
<< "\tName of Borrower: " << name
<< "\n\nMonth\t\tMonthly Amortization\t\tOutstanding Balance"
<< "\n";
for(n = 1; n <= Months; n++) {
MonthlyAmortization = TotalLoanAmount / Months;
OutstandingBalance = TotalLoanAmount - MonthlyAmortization;
cout << n << "\t\t" << MonthlyAmortization << "\t\t\t" << n - 1 << OutstandingBalance << endl;
}
cout << "\nEnd of Transaction";
cout << "Do you want to compute another transaction?[y/n]?" << endl;
cin >> ans;
}
while(ans == 'y');
}
After your cin>>ans, add these two lines :
cin.clear();
cin.sync();
That usually fixes a lot of the infinite looping problems I get with cin.
Also, I would recommend against initializing ans as 'y' when you declare it. I don't think this is causing you problems but it's an uncessesary thing.
You seem to expect pressing y and enter to register as only 'y'. If you want to get the input of just one character have a look at std::cin.get(char)

How do I incorporate input validation in this code?

I am trying to implement input validation into this program but it keeps coming out wrong. I tried using another while statement but it didn't work. It normally pops up with the text which shouldn't be. I want it to show after the person inputs the wrong information. I want it so that if the data entered is invalid, they will have to re enter it.
Here is the code I have so far.
/*
1. Declare variables for month 1, 2, and 3.
2. Declare variable for Total and Average Rainfall
3. Ask user to input name of months.
4. Then ask user to input inches of rain fall.
5. Add all inches and then divide by number of inches asked. In this case, 3.
6. Display average inches of rain for all months to user.
*/
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
string month1, month2, month3;//Declared values for months aswell as total and average rainfall.
double month1Inch, month2Inch, month3Inch;
double averageInches;
double totalInches;
char c = 'y';
do
{
cout << setprecision(2) << fixed;
cout << "Enter first month's name:";
cin >> month1;
cout << "Enter rain inches for " << month1 << ":";
cin >> month1Inch;
cout << "\n";
cout << "Enter second month's name:";
cin >> month2;
cout << "Enter rain inches for " << month2 << ":";
cin >> month2Inch;
cout << "\n";
cout << "Enter third month's name:";
cin >> month3;
cout << "Enter rain inches for " << month3 << ":";
cin >> month3Inch;
cout << "\n";
totalInches = (month1Inch + month2Inch + month3Inch);
averageInches = (totalInches) / 3;//calculating the average
//Display calculated data.
cout << "The average rainfall for " << month1 << ", " << month2 << ", " << "and " << month3 << " is " << averageInches << endl;
cout << "Would you like to recalculate? Either enter Y to run or N to not." << endl;
cin >> c;
} while (c == 'Y'||c=='y');
if (c != 'Y' || c != 'y')
cout << "you must enter the correct choice" << endl;
system("pause");
return 0;
}
I tried putting an if statement under "cout << "Would you like to recalculate? Either enter Y to run or N to not." << endl;
cin >> c;" but i get an infinite loops.
I am not getting any error codes. Just the text showing up with "would you like to recalculate?" line and infinite loops.
Even when I input the data with that showing, I get an infinite loop somewhere. So I deleted it.
It sounds like you want to validate the Yes or No response. That requires a loop that exits only when you have an acceptable input. It's separate from the loop that decides if the calculation should be run again.
int main() {
// ...
do {
// ...
do {
cout << "Would you like to recalculate? Either enter Y to run or N to not." << endl;
cin >> c;
} while (c != 'Y' && c != 'y' && c != 'N' && c != 'n');
} while (c == 'Y'|| c=='y');
system("pause");
return 0;
}

C++ For Loop Problem?

Ok so i'm working on this project and its a travel expense program. Basically it just has some functions that gets info from the user. I'm having a problem with my for loop. The running total is messing up. The numbers end up like 2 or 4 numbers off of what there supposed to be. Here's the code(I know it's not neat or anything i will clean that up later)
#include <iostream>
#include <fstream>
using namespace std;
int getDays(int);
double getDepartureTime();
double getArrivalTime(double);
double airFees(double);
double carRentalFees(double);
double getMilesDriven(double);
double getParkingTotal(double,double);
double getParkingSpent(double,double);
double getTaxiFees(double,double);
double employeeHotelExpense(double,double);
double getHotelExpense(double,double);
double getMealExpenses(double,double);
void timeEquivalent();
double breakFastFee = 0;
int main()
{
int days=0, amount=0, departure_conference=0, departure_home=0,time = 0;
double airFee=0,taxiFeesAllowed,parkingAllowed = 0,employeeHotelExpense = 0,employeeTaxiFees = 0, milesDriven=0,
parkingFees=0, taxiFees=0, yes=0,arrivalTime = 0;
double carRentalFee = 0, hotel_expenses=0,departureTime = 0, meals=0,employeeMealExpenses = 0, parkingSpent = 0,allowableHotelExpense = 0
,allowedMealTotal = 0,mealsSpent = 0;
char employee[40];
//timeEquivalent();
//cout << "What Time Did You Arrive " <<endl;
//cin >>time;
days = getDays(days);
timeEquivalent();
departureTime = getDepartureTime();
arrivalTime = getArrivalTime(arrivalTime);
airFee = airFees(airFee);
carRentalFee = carRentalFees(carRentalFee);
milesDriven = getMilesDriven(milesDriven);
parkingAllowed = 6 * days;
parkingSpent = getParkingSpent(parkingSpent,days);
taxiFeesAllowed = days * 10;
employeeTaxiFees = getTaxiFees(taxiFees,days);
allowableHotelExpense = 90 * days;
employeeHotelExpense = getHotelExpense(employeeHotelExpense, days);
employeeMealExpenses = getMealExpenses(departureTime,arrivalTime);
cout << employeeMealExpenses <<endl;
return 0;
}
int getDays(int days)
{
cout << " How many Days did you stay on the trip " <<endl;
cin >> days;
while(days < 0)
{
cout <<"Please enter a value greater than 0 :D " <<endl;
cin >> days;
}
return days;
}
double getDepartureTime()
{
double departureTime;
cout << "Please Refer To The Menu Above and enter the time of departure in military\n";
cout << "Time. For example if you departed at 7:30 enter 0730\n\n";
cin >> departureTime;
return departureTime;
}
double getArrivalTime(double arrivalTime)
{
cout << "Please refer to the menu above and enter the time you arrived back home in\n";
cout <<" military format\n";
cin >> arrivalTime;
return arrivalTime;
}
double airFees(double airfee)
{
cout << " How Much Were Your Air Fees " <<endl;
cin >> airfee;
while(airfee < 0)
{
cout <<" Please enter a value greater than 0 :D " <<endl;
cin >> airfee;
}
return airfee;
}
double carRentalFees(double carRentalFee)
{
cout << " How Much were Your Car Rental Fees " <<endl;
cin >> carRentalFee;
while(carRentalFee < 0)
{
cout <<"Please enter a value of 0 or greater :D " <<endl;
cin >> carRentalFee;
}
return carRentalFee;
}
double getMilesDriven(double milesDriven)
{
const double mileRate = 0.27;
cout << " How many miles did you drive, please enter 0 if a private vehicle was not used " <<endl;
cin >> milesDriven;
while(milesDriven < 0)
{
cout << " Please Enter 0 or Greater:)"<<endl;
cin >> milesDriven;
}
return mileRate * milesDriven;
}
double getParkingSpent(double parkingSpent, double days)
{
cout << " How Much Did You Spend on Parking " <<endl;
cin >> parkingSpent;
while(parkingSpent < 0)
{
cout << "Please Enter an Amount of 0 or Greater "<<endl;
cin >> parkingSpent;
}
return parkingSpent*days;
}
double getTaxiFees(double taxiFees,double days)
{
cout << " Please Enter The Amount of Taxi Fees Please " <<endl;
cin >> taxiFees;
while(taxiFees < 0)
{
cout << "Please Enter an Amount of 0 or Greater "<<endl;
cin >> taxiFees;
}
return taxiFees * days;
}
double getHotelExpense(double employeeHotelExpense,double days)
{
cout << " How Much Were Your Hotel Expenses " <<endl;
cin >> employeeHotelExpense;
while(employeeHotelExpense < 0)
{
cout << "Please Enter a Amount of 0 or Greater "<<endl;
cin >> employeeHotelExpense;
}
return employeeHotelExpense * days;
}
double getMealExpenses(double departureTime,double arrivalTime)
{
static double breakFastFee = 0 ;
static double lunchFee = 0 ;
static double dinnerFee = 0 ;
int numberOfDays = 2 ;
double total = 0;
for(int days =1;days <=numberOfDays;days++)
{
if ( days < numberOfDays && departureTime > 000 && departureTime < 700)
{
cout << "Please Enter Your breakfast cost"<<endl;
cin >> breakFastFee;
cout << " Please Enter Your Lunch Cost " <<endl;
cin >>lunchFee;
cout << "Please Enter Your Dinner Cost " <<endl;
cin >> dinnerFee;
}
if (days < numberOfDays && departureTime > 700 && departureTime <=1200)
{
cout << "Please Enter Your Lunch Cost"<<endl;
cin >> lunchFee;
cout << "Please Enter Your Dinner cost "<<endl;
cin >> dinnerFee;
}
if(days < numberOfDays && departureTime > 1201 && departureTime <= 1800)
{
cout << "Enter The Cost of Dinner " <<endl;
cin >> dinnerFee;
}
if(days == numberOfDays && arrivalTime > 800 && arrivalTime<=1300)
{
cout <<"Enter The Cost of Breakfast " <<endl;
cin >> breakFastFee;
}
if(days == numberOfDays && arrivalTime > 1301 && arrivalTime <= 1900)
{
cout << "Enter The Cost of Breakfast "<<endl;
cin >> breakFastFee;
cout << " Enter The Cost of Lunch " <<endl;
cin >> lunchFee;
}
if(days == numberOfDays && arrivalTime > 1901)
{
cout << "Enter The Cost of Breakfast " <<endl;
cin >> breakFastFee;
cout << " Enter The Cost of Lunch " <<endl;
cin >> lunchFee;
cout << "Enter The Cost of Dinner " <<endl;
cin >> dinnerFee;
}
total+=breakFastFee + lunchFee + dinnerFee;
}
return total;
}
void timeEquivalent()
{
cout <<"Regular Time " << "\t\t" <<"Military Time \n";
cout <<"************" << "\t\t" <<"***************"<<endl;
cout <<"Midnight " << "\t\t" <<"0000 \n";
cout <<"1:00a.m. " << "\t\t" <<"0100 \n";
cout <<"2:00a.m. " << "\t\t" <<"0200 \n";
cout <<"3:00a.m. " << "\t\t" <<"0300 \n";
cout <<"4:00a.m. " << "\t\t" <<"0400 \n";
cout <<"5:00a.m. " << "\t\t" <<"0500 \n";
cout <<"6:00a.m. " << "\t\t" <<"0600 \n";
cout <<"7:00a.m. " << "\t\t" <<"0700 \n";
cout <<"8:00a.m. " << "\t\t" <<"0800 \n";
cout <<"9:00a.m. " << "\t\t" <<"0900 \n";
cout <<"10:00a.m." << "\t\t" <<"1000 \n";
cout <<"11:00a.m." << "\t\t" <<"1100 \n";
cout <<"12:00p.m." << "\t\t" <<"1200 \n";
cout <<"1:00p.m. " << "\t\t" <<"1300 \n";
cout <<"2:00p.m. " << "\t\t" <<"1400 \n";
cout <<"3:00p.m. " << "\t\t" <<"1500 \n";
cout <<"4:00p.m. " << "\t\t" <<"1600 \n";
cout <<"5:00p.m. " << "\t\t" <<"1700 \n";
cout <<"6:00p.m. " << "\t\t" <<"1800 \n";
cout <<"7:00p.m. " << "\t\t" <<"1900 \n";
cout <<"8:00p.m. " << "\t\t" <<"2000 \n";
cout <<"9:00p.m. " << "\t\t" <<"2100 \n";
cout <<"10:00p.m." << "\t\t" <<"2200 \n";
cout <<"11:00p.m." << "\t\t" <<"2300 \n";
cout <<"Midnight " << "\t\t" <<"0000 \n";
}
can somebody tell me whats going wrong. If you test it out use 0600 for departure time and 0900 for arrivaltime.
There are multiple problems in this code. One, in a function like getDays that returns the number of days, you don't need to pass the number of days into the method as a parameter.
Also, since you want a value for days that is greater than 0, you should be checking whether days <= 0 in the while loop. Your current condition, days < 0, will be false if days is set to 0.
getDays would be better written as:
int getDays()
{
int days = 0;
cout << " How many Days did you stay on the trip " <<endl;
cin >> days;
while(days <= 0)
{
cout <<"Please enter a value greater than 0 :D " <<endl;
cin >> days;
}
return days;
}
Also, in getMealExpenses, there seems to be no reason to declare breakFastFee, lunchFee, and dinnerFee as static. This may be the cause of the problem you asked about, since they never get re-initialized to 0 after the first call to getMealExpenses.
Finally, neatly-formatted code is more likely to get helpful responses, because it's easier to read :-)
I think its becouse you are not resetting the breakFastFee, lunchFee, dinnerFee variable to 0 before each execution. So when total+=breakFastFee + lunchFee + dinnerFee; hits it will add values from the previues iteration.