Don't understand why output is incorrect - c++

I'm currently doing a Zybooks lesson for my C++ class and we're going over while loops. In this question, it wants me to calculate how many years it takes for a bank account to double it's initial balance. There is also an annual contribution added. My code is as follows:
#include <iostream>
using namespace std;
int main()
{
const double RATE = 5;
const double INITIAL_BALANCE = 10000;
const double TARGET = 2 * INITIAL_BALANCE;
cout << "Annual contribution: " << endl;
double contribution;
cin >> contribution;
double balance = INITIAL_BALANCE;
int year = 0;
while (balance < TARGET)
{
year++;
double interest = balance * RATE / 100;
balance = balance + interest + contribution;
}
cout << "Year: " << year << endl;
cout << "Balance: " << balance << endl;
return 0;
}
I used this as an answer but was met with this unexpected result:
Output differs. See highlights below.
Input
100
Your output
Annual contribution:
Year: 13
Balance: 20627.8
Expected output
Annual contribution:
Year: 13
Balance: 20527.8

I see the expected output and your output differs by a 100, i.e. your contribution. Maybe the evaluation system doesn't add annual contribution once your target is reached. The below code gets your required output, but I think your code should have been the correct answer.
#include <iostream>
using namespace std;
int main()
{
const double RATE = 5;
const double INITIAL_BALANCE = 10000;
const double TARGET = 2 * INITIAL_BALANCE;
cout << "Annual contribution: " << endl;
double contribution;
cin >> contribution;
double balance = INITIAL_BALANCE;
int year = 0;
while (balance < TARGET)
{
year++;
double interest = balance * RATE / 100;
balance = balance + interest;
if (balance < TARGET) {
balance += contribution;
}
}
cout << "Year: " << year << endl;
cout << "Balance: " << balance << endl;
return 0;
}

The problem is that you're making a contribution after the 13th year even though the target has been reached.
I would restructure to something like this, in order to only check the condition once:
while (true)
{
year++;
double interest = balance * RATE / 100;
balance += interest;
if (balance >= TARGET)
{
break;
}
balance += contribution;
}

This is because the last time the loop is being executed (at year=13), balance is less than TARGET but, after adding a contribution and interest into it, it jumps out of the loop with contribution and interest added to it.
So, the solution can be to use an if statement within the while loop to check if it exceeds the TARGET; if it does, then don't add contribution into it.
Replace your while loop with the following:
while (balance < TARGET)
{
year++;
double interest = balance * RATE / 100;
balance = balance + interest;
if (balance < TARGET) {
balance += contribution;
}
}

Related

C++ Why is this outputting the wrong compound interest?

I've been trying to figure this out for sometime and I think it has something to do with the values I'm using for the calculations. I'm not exactly familiar with compound interest so I'm not sure were I'm going wrong. Any help would be appreciated.
#include <iostream>
#include <cmath>
using namespace std;
double interest_credit_card(double initial_balance, double interest_rate, int payment_months);
// Calculates interest on a credit card account according to initial balance,
//interest rate, and number of payment months.
int main ()
{
double initial_balance, interest_rate;
int payment_months;
char answer;
do
{
cout << "Enter your initial balace: \n";
cin >> initial_balance;
cout << "For how many months will you be making payments?\n";
cin >> payment_months;
cout << "What is your interest rate (as a percent)?: %\n";
cin >> interest_rate;
cout << endl;
cout << "You will be paying: $ " << interest_credit_card( initial_balance, interest_rate, payment_months) << endl;
cout << "Would you like to try again? (Y/N)\n";
cin >> answer;
}while (answer == 'Y' || answer == 'y');
cout << "Good-Bye.\n";
return 0;
}
double interest_credit_card(double initial_balance, double interest_rate, int payment_months)
{
double compound_interest, compounding, compounding2, compounding3, compounding4;
while(payment_months > 0)
{
initial_balance = initial_balance + (initial_balance * interest_rate/100.0);
compounding = (interest_rate /12);
compounding2 = compounding + 1;
compounding3 = interest_rate * (payment_months/12);
compounding4 = pow(compounding2, compounding3);
compound_interest = initial_balance * compounding4;
initial_balance = initial_balance + compound_interest;
payment_months--;
}
return initial_balance;
}
Inputs and expected outputs:
Enter your initial balance: 1000
For how many months will you be making payments?: 7
What is your interest rate (as a percent)?: 9
You will be paying: $1053.70
It looks like you were trying a bunch of things and then left them in. The first solution you tried was almost right, you just forgot "/12":
double interest_credit_card(double initial_balance, double interest_rate, int payment_months)
{
while (payment_months > 0)
{
initial_balance = initial_balance + (initial_balance * interest_rate / 100.0/12);
payment_months--;
}
return initial_balance;
}
With a little better style:
double interest_credit_card(double initial_balance, double interest_rate, int payment_months)
{
double total_payment = initial_balance;
double monthly_rate = interest_rate / 100.0 / 12;
for (int month = 1; month <= payment_months; ++month)
total_payment += total_payment * monthly_rate;
return total_payment;
}

C++ Expression preceding parentheses

I'm currently working on a set of code where we had to rework the code from all being written in the main and breaking it up into two subfunctions and the main. I've broken it up, but I am having trouble reading in one of my subfunctions. I never learned parameter passing in depth because my professor only briefly touched on it.
The error I'm getting is "Expression preceding parentheses of apparent call must have (pointer-to-) function type."
This is the line of code I'm having an issue with:....
type = selectCarpet(type, unitPrice);
unitPrice = oneRoom(pricePerSqYd, count, ftLength, ftWidth, ftSq, ydSq, squareYd, materialCost, totalCost, unitPrice);
and this is the function:
#include <iostream>
#include <iomanip>
#include <conio.h>
#include <string>
using namespace std;
const double BEST = 6.99,
MEDIUM = 4.59,
BASIC = 3.50,
INSTALL = 129.99;
const int NINE = 9;
int selectCarpet(int type, int unitPrice);
double oneRoom(double pricePerSqYd, int count, double ftLength, double ftWidth, int numRooms, double ftSq, double ydSq, int squareYd, double materialCost, double unitPrice, double totalCost);
int main()
{
double ftLength, // room length in feet
ftWidth, // room width in feet
ftSq, // square footage
ydSq, // square yard
materialCost, // carpet material cost
totalCost, // material cost plus install
grandTotal,
unitPrice;
int squareYd, // square yards, round off
type, // carpet type
count,
numRooms;
type = 0;
unitPrice = 0;
double pricePerSqYd,
oneRoom;
type = selectCarpet(type, unitPrice);
totalCost = 0;
cout << "\nEnter number of rooms: ";
cin >> numRooms;
unitPrice = oneRoom(pricePerSqYd, count, ftLength, ftWidth, ftSq, ydSq, squareYd, materialCost, totalCost, unitPrice);
// step 11
grandTotal = 0;
grandTotal += totalCost;
cout << "\n\nThe grand total price is "
<< grandTotal << endl;
// step 13
do
{
cout << "\n\t\t*** CARPET INSTALLATION ***\n\n";
cout << "Select carpet type:\n"
<< "1 - Best Quality, Unit Price $6.99\n"
<< "2 - Medium Quality, unit price $4.59\n"
<< "3 - Basic Quality, Unit price $3.50\n"
<< "4 - exit\n"
<< "Enter your choice --> ";
cin >> type;
} while (type != 1 && type != 2 && type != 3 && type != 4);
return 0;
}
int selectCarpet(int type, int unitPrice)
{
do
{
cout << "\n\t\t*** CARPET INSTALLATION ***\n\n";
cout << "Select carpet type:\n"
<< "1 - Best Quality, Unit Price $6.99\n"
<< "2 - Medium Quality, unit price $4.59\n"
<< "3 - Basic Quality, Unit price $3.50\n"
<< "4 - exit\n"
<< "Enter your choice --> ";
cin >> type;
} while (type != 1 && type != 2 && type != 3 && type != 4);
while (type != 4)
{
// step 2
if (type == 1) unitPrice = BEST;
else if (type == 2) unitPrice = MEDIUM;
else if (type == 3) unitPrice = BASIC;
}
return unitPrice;
}
double oneRoom(double pricePerSqYd, int count, double ftLength, double ftWidth, int numRooms, double ftSq, double ydSq, int squareYd, double materialCost, double unitPrice, double totalCost)
{
for (count = 0; count < numRooms; count++)
{
cout << "Enter room length in feet: ";
cin >> ftLength;
cout << "Enter room diwth in feet: ";
cin >> ftWidth;
// step 5
ftSq = ftLength * ftWidth;
// step 6
ydSq = ftSq / NINE;
// step 7
squareYd = int(ydSq + .5);
// step 8
materialCost = squareYd * unitPrice;
// step 9
totalCost = materialCost + INSTALL;
// step 10
cout << setiosflags(ios::fixed | ios::showpoint)
<< setprecision(2);
cout << "\n\nSquare footage of the room is: " << ftSq
<< "\nSquare yard of the room is:\t" << ydSq
<< "\nSquare yards priced for: " << squareYd
<< "\nMaterial Cost:\t$" << materialCost
<< "\nInstallation\t$" << INSTALL
<< "\nTotal Cost\t$" << totalCost
<< endl << endl;
}
return pricePerSqYd;
}
any help is appreciated as I have almost no idea what I am doing here. Thank you.
This declaration within main():
double pricePerSqYd,
oneRoom;
shadows the declaration of your function outside of main():
double oneRoom(..., ...);
Name lookup finds the variable first, but you can't call a double. Hence the error. Just rename one or the other.

C++ Airfare Charge Calculation project

I have to create a program to calculate charges for airfare. It's a simple program so far and I am not done adding to it, but every time I run it the result turns out to be 0. Is there something missing in my code? I am a beginner and I would appreciate any advice on improving my code. Thank you.
#include <iostream>
using namespace std;
void main () {
int distance = 0;
int num_bags= 0;
int num_meals= 0;
double distance_price = distance * 0.15;
double bag_price = num_bags * 25.00;
double meal_price = num_meals * 10.00;
double total_airfare = 0.00;
cout << "CorsairAir Fare Calculator" << endl;
cout << "Enter the distance being travelled: " << endl;
cin >> distance;
cout << "Enter number of bags checked: " <<endl;
cin >> num_bags;
cout << "Enter the number of meals ordered: " << endl;
cin >> num_meals;
total_airfare = (distance_price + bag_price + meal_price);
cout << total_airfare;
}
Your confusion is completely understandable - the piece you're missing is that when you assign a variable, you're assigning the left side to the result of the right side at that moment in time. It's not like algebra, where you say f(x) = x + 5 and f(x) is always whatever x + 5 is.
So, you assign double distance_price = distance * 0.15 when distance is 0 (which you just initialized). distance_price remains 0 even after you ask for input and change distance.
Do your price calculations after you ask for input, and everything will work just fine.
You are calculating the distance_price bag_price meal_price with default values i.e. 0 not with the value which you took from user.
Below code works fine and you won't see the issue.
#include <iostream>
using namespace std;
// My compiler did not allow void main so used int main
int main () {
int distance = 0;
int num_bags= 0;
int num_meals= 0;
double distance_price ;
double bag_price ;
double meal_price;
double total_airfare;
cout << "CorsairAir Fare Calculator" << endl;
cout << "Enter the distance being travelled: " << endl;
cin >> distance;
cout << "Enter number of bags checked: " <<endl;
cin >> num_bags;
cout << "Enter the number of meals ordered: " << endl;
cin >> num_meals;
distance_price = distance * 0.15;
bag_price = num_bags * 25.00;
meal_price = num_meals * 10.00;
total_airfare = 0.00;
total_airfare = distance_price + bag_price + meal_price;
cout << total_airfare;
return 0;
}
Result
CorsairAir Fare Calculator
Enter the distance being travelled:
200
Enter number of bags checked:
2
Enter the number of meals ordered:
2
100

C++ Calculation Problem, Always returns $0

I have to display and loop a menu, allowing the customer to make multiple orders for peanuts, movies, or books. The menu displays fine, but the quantity doesn't go down to the calculations part of my code. Everytime I enter a quantity for anything and checkout it returns $0. I have no idea why this is happening I don't see anything wrong with my code, but obviously there is. Do you guys have any suggestions on what to do based on looking at what I have?
#include <iostream>
#include <cstdlib>
using namespace std;
//function declarations
void displayMenu();
//constant statements
const double BOOK_PRICE = 9.00; //price per book
const double BOOK_SHIPPING = 1.06; //shipping per book
const double MOVIE_PRICE = 13.99; //price per movie
const double MOVIE_SHIPPING = .05; //shipping per movie subtotal
const double PEANUT_PRICE = 1.80; //price of peanuts per pound
const double SHIPPING_PRICE = .50; //shipping of peanuts per lb
int main()
{
//declaration statements
int numBooks = 0; //# of books purchased
int numMovies = 0; //# of movies purchased
double numPeanuts = 0.0; //# of peanuts per pound
double bookSubtotal = 0.0; //subtotal of books
double movieSubtotal = 0.0; //subtotal of movies
double peanutSubtotal = 0.0; //subtotal of peanuts
int totalBooks = 0; //running total of books
int totalMovies = 0; //running total of movies
double totalPeanuts = 0.0; //running total of peanuts
int userChoice = 0; //user input
double totalPrice = 0.0; //final price
while (userChoice != 4)
{
displayMenu();
cout << "Enter a menu choice: ";
cin >> userChoice;
if (userChoice == 1)
{
cout << "Please enter the number of books: ";
cin >> numBooks;
totalBooks = totalBooks + numBooks;
}
else if (userChoice == 2)
{
cout << "Please enter the number of movies: ";
cin >> numMovies;
totalMovies = totalMovies + numMovies;
}
else if (userChoice == 3)
{
cout << "Please enter the pounds of peanuts as a decimal: ";
cin >> numPeanuts;
totalPeanuts = totalPeanuts + numPeanuts;
}
else if (userChoice == 4)
{
break;
}
else
{
cout << "Invalid Input" << endl;
}
}
//computations
bookSubtotal = (totalBooks * BOOK_PRICE) + (totalBooks * BOOK_SHIPPING);
movieSubtotal = (totalMovies * MOVIE_PRICE * .05) + (totalMovies * MOVIE_PRICE);
peanutSubtotal = (PEANUT_PRICE * totalPeanuts) + (totalPeanuts * .5);
totalPrice = bookSubtotal + movieSubtotal + peanutSubtotal;
cout << "The total price is $" << totalPrice << endl;
system("PAUSE");
return 0;
}//end of main
void displayMenu()
{
cout << "1 Books" << endl;
cout << "2 Movies" << endl;
cout << "3 Peanuts" << endl;
cout << "4 Checkout" << endl;
}//end of displayMenu
The problem is in the cin >> - you found the answer yourself when you say that the book count is zero. I suggest you try to put << endl after each cout << .... Other solution is to use _flushall(); after each cout.

How do I fix my while Error?

I'm writing a program in Microsoft Visual Studio with C++ that will retrieve information from a .txt file. In that file there are negative numbers, but when I try to write a while loop that states what to do if there is a negative number, I get several errors.
Can someone please help me with this? Here is my code and I do realize there are errors but I can't figure out how to write the While loop statement to read these values which are hours worked and the hourly rate from the .txt file
Sample text file:
45.0 10.50
-35.0 7.75
50.0 12.00
45.0 -8.50
30.0 6.50
48.0 -10.25
-50.0 10.00
50.0 8.75
40.0 12.75
56.0 8.50
Code:
//*****************************
// This program is to help calculate an employee's weekly gross pay as well as
// the net pay while showing the taxes that were taken off.
// The data that will be shown will be calculated from a .txt file
// that was created and called employee.txt.
// Input: Will be the inFile known as employee.txt
// Output: Gross pay, taxable income, federal tax, state tax, and net pay
// Typed by:
// Date:
//******************************
#include <iomanip>
#include <fstream>
#include <iostream>
using namespace std;
float computeGross(float, float);
void computeTaxes(float, float&, float&, float&);
float computeNetPay (float&, float&, float&, float&);
const float hours = 40; // Regular 40 hour work week
const float ovTime = 1.5; // Overtime if hours go over 40
const float exemption = 200.0; // Exemption if pay goes over 200
const float fedTaxRate = 0.10; // Federal Tax Rate
const float stTaxRate = 0.03; // State Tax rate
ifstream inFile;
ofstream outFile;
int main()
{
inFile.open("employee.txt");
outFile.open("result.txt");
float hours, rate, grossPay, taxableIncome, fedTax, stTax, NetPay;
inFile >> hours >> rate;
while(inFile)
{
if {
(hours <= 0)&& (rate <= 0);
outFile << "Invalid Data";
}
else{
return 0;
}
}
grossPay = computeGross(hours, rate);
computeTaxes (grossPay, taxableIncome, fedTax, stTax);
computeNetPay (grossPay, fedTax, stTax, NetPay);
outFile << fixed << showpoint << setprecision(2);
outFile << "Hours worked = " << hours << endl
<< "Hourly rate = " << rate << endl
<< "Employee's gross pay = " << grossPay << endl
<< "Taxable Income = " << taxableIncome << endl
<< "Federal Taxes = " << fedTax << endl
<< "State Taxes = " << stTax << endl
<< "Net Pay = " << NetPay << endl;
return 0;
}
float computeGross (float h, float r) //Computes for the Gross Pay
{
if (h > hours)
return hours * r + (h - hours) * r * ovTime;
else
return h * r;
}
void computeTaxes(float g, float& taxable, float& fedTax, float& stTax) //Computes both Taxes
{
taxable = g - exemption;
if (taxable > 0.0)
{
fedTax = fedTaxRate * taxable;
stTax = stTaxRate * taxable;
}
else
{
fedTax = 0.0;
stTax = 0.0;
}
}
float computeNetPay (float& grossPay, float& fedTax, float& stTax, float& NetPay)
{
return NetPay = grossPay - fedTax - stTax;
}
In your main function you have:
while(inFile)
{
if ((hours <= 0) && (rate <= 0))
{
outFile << "Invalid Data";
}
else {
return 0;
}
}
When the else is triggered the program finishes, the main function returns. You might want a continue break or nothing here instead, that return statement ends the main function not the While loop.
To get all the data out of the file your read statement ( inFile >> hours >> rate);
will need to be in this or another loop. Say after the IF test for validity, it could be in the Else.
while(inFile)
{
if ((hours <= 0) && (rate <= 0)) {
outFile << "Invalid Data";
}
else {
// call the data functions
// save the returned values
}
//prime hours and rate for the next loop
inFile >> hours >> rate;
}
Well.. my guess is this is what your looking for:
Note that the:
if ((hours <= 0) && (rate <= 0))
is changed to:
if ((hours <= 0) || (rate <= 0))
otherwise it won't ever hit the "invalid data" with your supplied data
//*****************************
// This program is to help calculate an employee's weekly gross pay as well as
// the net pay while showing the taxes that were taken off.
// The data that will be shown will be calculated from a .txt file
// that was created and called employee.txt.
// Input: Will be the inFile known as employee.txt
// Output: Gross pay, taxable income, federal tax, state tax, and net pay
// Typed by:
// Date:
//******************************
#include <iomanip>
#include <fstream>
#include <iostream>
using namespace std;
float computeGross(float, float);
void computeTaxes(float, float&, float&, float&);
float computeNetPay (float&, float&, float&, float&);
const float hours = 40; // Regular 40 hour work week
const float ovTime = 1.5; // Overtime if hours go over 40
const float exemption = 200.0; // Exemption if pay goes over 200
const float fedTaxRate = 0.10; // Federal Tax Rate
const float stTaxRate = 0.03; // State Tax rate
int main()
{
ifstream inFile ("employee.txt");
ofstream outFile ("result.txt");
float hours, rate, grossPay, taxableIncome, fedTax, stTax, NetPay;
if (inFile.is_open())
{
while (! inFile.eof() )
{
inFile >> hours;
inFile >> rate;
if ((hours <= 0) || (rate <= 0))
{
outFile << "Invalid Data";
}
else
{
grossPay = computeGross(hours, rate);
computeTaxes (grossPay, taxableIncome, fedTax, stTax);
computeNetPay (grossPay, fedTax, stTax, NetPay);
outFile << fixed << showpoint << setprecision(2);
outFile << "Hours worked = " << hours << endl
<< "Hourly rate = " << rate << endl
<< "Employee's gross pay = " << grossPay << endl
<< "Taxable Income = " << taxableIncome << endl
<< "Federal Taxes = " << fedTax << endl
<< "State Taxes = " << stTax << endl
<< "Net Pay = " << NetPay << endl;
}
}
}
return 0;
}
The rest is the same
For a start, I think that this:
if {
(hours <= 0)&& (rate <= 0);
outFile << "Invalid Data";
}
Should be this:
if ((hours <= 0) && (rate <= 0)) {
outFile << "Invalid Data";
}
Note that to get code to format properly on StackOverflow, you should only use spaces, not tabs. I think that's whats causing your format issues.