Having some trouble with a assignment in c++ - 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";

Related

C++: interestEarned coming back wrong

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

Why am I being prompted with an error message stating that Y may be used uninitialized when I initialized it?

I just started writing C++ not too long ago. For my class, we were asked to write a program that allows the user to input data and then print out the data respectively. I wanted to verify that the user inputted their data incorrectly so I added an if-else statement. However, when I run the program it says warning: 'Y' may be used uninitialized in this function [-Wmaybe-uninitialized]
if (V == Y || V == y) {
It says this for Y, y, N, and n. What am I doing wrong? I thought I initialized these variables in the char assignment statement... Here is my code:
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
int principle;
double rate, time, interest, initInvest, total;
char V, Y, y, N, n;
cout << "Enter the initial amount of your investment: ";
cin >> initInvest;
cout << "The amount of your initial investment has been set to " << initInvest << "."
<< "\n\nEnter the investment principle as a real number: ";
cin >> principle;
cout << "The investment principle has been set to " << principle << "."
<< "\n\nEnter the amount of time that has passed since the initial deposit: ";
cin >> time;
cout << "The amount of time passed since the initial deposit has been set to " << time << "."
<< "\n\nEnter the investment rate as a decimal number: ";
cin >> rate;
cout << "The investment rate has been set to " << rate << ".\n\n"
<< "Please verify that the above values are correct Y/N: "; //verifies data in case user inputed values incorrectly
cin >> V; //verification value
if (V == Y || V == y) {
interest = principle*rate*time; //calculates interest earned
total = initInvest+interest; //calculates total amount earned
cout << setiosflags(ios::showpoint) << fixed << setprecision(3); //sets output for all floating-point values
cout << "INITIAL INVESTMENT INTEREST EARNED TOTAL AMOUNT EARNED\n" //creates a neat table to
<< "------------------ --- --------------- --- -------------------\n" //display the gathered data
<< setw(18) << initInvest << setw(20) << interest << setw(24) << total << endl;
}
else if (V == N || V == n) { //re-initiates all before stated data
cout << "\nPlease re-enter the data and try again.\n"
<< "Enter the initial amount of your investment: ";
cin >> initInvest;
cout << "The amount of your initial investment has been set to " << initInvest << "."
<< "\n\nEnter the investment principle as a real number: ";
cin >> principle;
cout << "The investment principle has been set to " << principle << "."
<< "\n\nEnter the amount of time that has passed since the initial deposit: ";
cin >> time;
cout << "The amount of time passed since the initial deposit has been set to " << time << "."
<< "\n\nEnter the investment rate as a decimal number: ";
cin >> rate;
cout << "The investment rate has been set to " << rate << ".\n\n"
<< "Please review the output values.\n"
<< "If they are still not correct, restart the program."; //gave the user a second chance to get it right
}
return 0;
}
To compare V with the character y, you should write V == 'y' (a character literal is written between single quotes).
The declaration char y; creates a variable named y that can store any character.
Hey Thats Wrong Way Of Testing The Condition.
if (V == Y || V == y) { //Wrong Way
It Should Be
if (V == 'Y' || V == 'y') {

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;
}

Solution for printing information to the screen in c++?

I have to make a loop to gather all the information from the users input of the employees. As you can see, I have gotten the parts where I ask the user how many employees and what their information is. Now all I have to is print that information to the screen like this, just without the periods between each and with a few spaces between each :
Weekly Payroll:
Name...............Title........Gross.......Tax.........Net
----------------------------------------
Ebenezer Scrooge.....................Partner...250.00......62.25.....187.75
Bob Cratchit...............................Clerk.......15.00........2.00.......13.00
And this is what I have :
#include <iostream>
using namespace std;
const int MAXSIZE = 20;
struct EmployeeT
{
char name[MAXSIZE];
char title;
double SSNum;
double Salary;
double Withholding_Exemptions;
};
EmployeeT employees[MAXSIZE];
int main()
{
cout << "How many Employees? ";
int numberOfEmployees;
cin >> numberOfEmployees;
while(numberOfEmployees > MAXSIZE)
{
cout << "Error: Maximum number of employees is 20\n" ;
cout << "How many Employees? ";
cin >> numberOfEmployees;
}
char name[MAXSIZE];
int title;
double SSNum;
double Salary;
double Withholding_Exemptions;
for (int count=0; count < numberOfEmployees; count++)
{
cout << "Name: ";
cin >> employees[ count ].name;
cout << "Title: ";
cin >> employees[ count ].title;
cout << "SSNum: \n";
cin >> employees[ count ].SSNum;
cout << "Salary: \n";
cin >> employees[ count ].Salary;
cout << "Withholding Exemptions: \n";
cin >> employees[ count ].Withholding_Exemptions;
}
double gross;
double tax;
double net;
double adjusted_income;
gross = employees[ count ].Salary;
adjusted_income = employees[ count ].Salary - 1.00;
tax = adjusted_income * .25;
net = gross - tax;
cout << "Weekly Payroll:\t Name \t Title \t Gross \t Tax \t Net \n";
for (int count=0; count < numberOfEmployees; count++)
{
cout << employees[count].name << " \t" << employees[count].title << " \t" <<
gross << "\t" << tax << "\t" << net << "\n";
}
system("pause");
}
Ok I updated the program. Now I'm trying to do the calculations. This what I'm doing...
To calculate payroll:
Gross pay is the weekly salary which was previously entered for the employee.
Net pay is calculated as the gross pay minus the amount of tax.
To calculate tax: Deduct $1 from the salary for each withholding exemption. This is the adjusted income. If the adjusted income is less than 0, then use 0 as the adjusted income.
Multiply the adjusted income by the tax rate, which you should assume is a flat 25%.
As an example, if Bob Cratchit has a weekly income of $15 and 7 dependents, then his adjusted income would be $8. His tax would be 25% of $8 which is $2, and therefore his net pay is $13.
I have started trying to get this. I put it between the second loop and the last loop. Is this right?
A small example for printing columns using C++ streams:
#include <iomanip>
#include <ios>
std::ostream& operator<<(std::ostream& a_out, const EmployeeT& a_e)
{
a_out << std::setfill(' ')
<< std::left
<< std::setw(sizeof(a_e.name))
<< a_e.name
<< std::setw(0)
<< a_e.title
<< " "
<< std::setw(10)
<< a_e.SSNum
<< a_e.Salary
<< a_e.Withholding_Exemptions;
return a_out;
}
This would allow you to write an employee to standard output using:
std::cout << employees[n] << "\n";
Use a similar approach for the column headings.
Other points:
Prefer std::string to char[] (or char*) then you don't have to limit the length of the string (or explicitly manage the memory)
Use std::vector instead of a fixed array to avoid a limit
Make use of STL algorithms (std::for_each, std::copy for example) for performing operations on elements in containers (or array)
you can use the same loop for insertion and displaying or anything!! because it traverses through the whole loop.
cout << "Weekly Payroll:\t Name \t Title \t Gross \t Tax \t Net \n";
for (int count=0; count < numberOfEmployees; count++)
{
cout << employees[count].name << " \t" << employees[count].title << " \t" <<
Gross << "\t" << tax << "\t" << Net << "\n";
}
Find net,tax and gross of each structure object and print.
Check if you want name as int at the marked position.
#include <iostream>
using namespace std;
const int MAXSIZE = 20;
struct EmployeeT {
char name[MAXSIZE];
char title;
double SSNum;
double Salary;
double Withholding_Exemptions;
};
EmployeeT employees[MAXSIZE];
int main() {
cout << "How many Employees? ";
int numberOfEmployees;
cin >> numberOfEmployees;
while(numberOfEmployees > MAXSIZE) {
cout << "Error: Maximum number of employees is 20\n" <<
"How many Employees? ";
cin >> numberOfEmployees;
}
int name; // name is char[] or string
int title;
double SSNum;
double Salary;
double Withholding_Exemptions;
for (int count = 0; count < numberOfEmployees; count++) {
cout << "Name: \n";
cin >> employees[ count ].name;
cout << "Title: \n";
cin >> employees[ count ].title;
cout << "SSNum: \n";
cin >> employees[ count ].SSNum;
cout << "Salary: \n";
cin >> employees[ count ].Salary;
cout << "Withholding Exemptions: ";
cin >> employees[ count ].Withholding_Exemptions;
}
}
You can use the '\t' sequence, which represent in C++ a "Tab space" (like when you press Tab on your Keyboard).
As for the loop, it should be something like:
cout << "Weekly Payroll:\t Name \t Title \t Gross \t Tax \t Net \n";
for(int n=0; n < employees; n++)
{
cout << employees[n].name << " \t" << employees[n].title << " \t" ...... << "\n";
}
It should work :)
You could look into the STL iomanip header functions, like setw()
Formatting Cout Output in C++ using iomanip
. With that it should be possible to get decent fix sized columns, which tabs likely wont.
Your code has seems OK, although it is more complicated than it should be, and the input-loop has no error-handling (if a user enters something invalid, your program will stop working).
Here are some general pointers that can help you make your program better:
Use std::vector<EmployeeT> instead of an array - this way you don't have to limit the number of employees you can handle, because the vector can grow dynamically.
Provide an operator<<-overload for EmployeeT.
Look into Iostream-manipulators, particularly std::setw; This question is similar to your problem, and one solution uses manipulators to format the output.