Program works and executes everything properly until I get to the part where the function calculates Annual Sales and Quarterly Averages. I'm not sure if the issue is in the function or in the displaying of the information.
The Annual Sales and Average Quarterly Sales display is -6.27744e+66
I feel like I'm missing something obvious.
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
struct Company
{
string dName; // Stores Division Name
double firstQSales; // First Quarterly Sales
double sndQSales; // Second Quarterly Sales
double thirdQSales; // Third Quarterly Sales
double fourthQSales; // Fourth Quarterly Sales
double annualSales; // Annual Quarterly Sales
double avgQSales; // Average Quarterly Sales
};
const double NUM_OF_QUARTERS = 4;
void readCorpSales(Company*, int);
void displaySalesData(Company*, int);
void calculateAnnualSales(Company&);
void calculateQuarterlyAvg(Company&);
int main()
{
int corporateSize;
cout << "How many divisions does your corporate has: ";
cin >> corporateSize;
cin.ignore();
while (corporateSize < 0)
{
cout << "Please enter a positive number: ";
cin >> corporateSize;
}
Company* divisions = new Company[corporateSize];
readCorpSales(divisions, corporateSize);
displaySalesData(divisions, corporateSize);
delete[] divisions;
system("pause");
return 0;
}
void readCorpSales(Company *divisions, int a)
{
for (int i = 0; i < a; ++i)
{
cout << "Enter division's name: ";
cin >> divisions[i].dName;
cout << "Enter 1st quarter sales: ";
cin >> divisions[i].firstQSales;
cout << "Enter 2nd quarter sales: ";
cin >> divisions[i].sndQSales;
cout << "Enter 3rd quarter sales: ";
cin >> divisions[i].thirdQSales;
cout << "Enter 4th quarter sales: ";
cin >> divisions[i].fourthQSales;
cout << "\n";
}
}
void displaySalesData(Company* divisions, int a)
{
cout << "\n===============================";
cout << "\n Corporate Data Sales Report";
cout << "\n===============================\n";
cout << "\nDivision Name";
cout << "\t 1st Q ($)";
cout << "\t 2nd Q ($)";
cout << "\t 3rd Q ($)";
cout << "\t 4th Q ($)";
cout << "\t Annual Sales ($)";
cout << "\t Avg Q Sales ($)\n";
for (int i = 0; i < a; ++i)
{
cout << divisions[i].dName << "\t";
cout << divisions[i].firstQSales << "\t";
cout << divisions[i].sndQSales << "\t";
cout << divisions[i].thirdQSales << "\t";
cout << divisions[i].fourthQSales << "\t";
cout << divisions[i].annualSales << "\t";
cout << divisions[i].avgQSales << "\n";
}
}
void calculateAnnualSales(Company &divisions)
{
divisions.annualSales = divisions.firstQSales + divisions.sndQSales + divisions.thirdQSales + divisions.fourthQSales;
}
void calculateQuarterlyAvg(Company &divisions)
{
divisions.avgQSales = divisions.annualSales / 4;
}
Regarding the garbage value, maybe you can refer to this or this.
Other thing, the answer from M.M covered the question
Related
I get an error of "no operator matches these operands" when using the part of the code outputFile << customerName << "your Monthly payments are " << monthlyPay << endl;. Overall, I need the code to Add the ability to save data to disk in one or more files and a menu should give the user the option to save or retrieve data. I have not gotten past the error to properly run the program. Can you please help fix error.
#include <iostream>
#include <string>
#include <cmath>
#include <iomanip>
#include <vector>
#include<fstream>
using namespace std;
void menu(void);
void writeData(void);
void readData(void);
const char FileName[] = "CourseProjectAvilaF.txt";
//Variables
vector <double> Loanlgth, Loanamt, interestRate, totalInterest;
vector <double> monthlyPay(100), loanTotal(100), creditScore(100);
vector <string> customerName;
int main()
{
menu();
return 0;
}
void menu(void)
{
const int INPUT_CUSTOMER = 1, DISPLAY_LOAN = 2, EXIT_PROGRAM = 3;
int option;
//Program
cout << "Thank you for choosing The Bank of UA for your loan requirements!\n\n";
do
{
cout << "UA Bank menu:\n\n"
<< "1. Enter your information\n"
<< "2. See your loan requirements\n"
<< "3. Exit program\n\n"
<< "Choose an option: ";
cin >> option;
while (option < INPUT_CUSTOMER || option > EXIT_PROGRAM)
{
cout << "Please enter a valid menu option: ";
cin >> option;
}
if (option == 1)
{
writeData();
}
if (option == 2)
{
readData();
}
} while (option != EXIT_PROGRAM);
}
//function to read customer information
void writeData(void)
{
fstream outputFile;
outputFile.open(FileName, fstream::app);
int index;
int numCustomers = 0;
cout << "Please enter the number of customers you would like\n"
<< " to enter loan information for: ";
cin >> numCustomers;
for (index = 0; index < numCustomers; index++)
{
string tempName;
double tempLoanamt, tempLoanlgth, tempcreditScore, tempinterestRate,
tempinterest;
cout << "Please enter your name: ";
cin >> tempName;
customerName.push_back(tempName);
cout << "Please enter the loan amount: $";
cin >> tempLoanamt;
Loanamt.push_back(tempLoanamt);
cout << "Please enter the length of the loan in months: ";
cin >> tempLoanlgth;
Loanlgth.push_back(tempLoanlgth);
cout << "What is your current credit score? ";
cin >> tempcreditScore;
creditScore.push_back(tempcreditScore);
//This will determine interest rate and overall loan amount when calculated
if (tempcreditScore <= 650)
tempinterestRate = .12;
else
tempinterestRate = .05;
interestRate.push_back(tempinterestRate);
//Calculations
tempinterest = Loanamt[index] * interestRate[index];
totalInterest.push_back(tempinterest);
loanTotal[index] = (Loanamt[index] + totalInterest[index]);
monthlyPay[index] = loanTotal[index] / Loanlgth[index];
// Out put files to write data to be saved
outputFile << customerName << "your Monthly payments are " << monthlyPay << endl;
outputFile << "Your total interest is " << totalInterest << endl;
outputFile << "You owe " << loanTotal << endl;
outputFile << "You have " << Loanlgth << " months to pay off your balance" << endl;
}
outputFile.close(); //Close file
}
//function loan information
void readData(void)
{
int index;
int numCustomers = 0;
ifstream inputFile;
inputFile.open(FileName, fstream::in);//Open the file with read mode
//Display monthly payment
cout << fixed << setprecision(2);
for (index = 0; index < numCustomers; index++)
{
cout << customerName[index] << " your total loan is " << loanTotal[index]
<< "\n"
<< "with a monthly payment of $" << monthlyPay[index] << "\n"
<< "for " << Loanlgth[index] << " months with an interest\n"
<< "rate of " << interestRate[index] << endl;
}
}
It's simple enough, you got it right everywhere else in your program.
When you want to access a particular element of a vector you use an index. Like this
outputFile << customerName[index] << "your Monthly payments are " << monthlyPay[index] << endl;
outputFile << "Your total interest is " << totalInterest[index] << endl;
outputFile << "You owe " << loanTotal[index] << endl;
outputFile << "You have " << Loanlgth[index] << " months to pay off your balance" << endl;
customerName and monthlyPay are vectors. You can't stream them directly. Instead you can do something like
for (auto const &name : customerName)
outputFile << name;
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";
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.
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
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)