C++ Calculation Problem, Always returns $0 - c++

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.

Related

Passing information obtained from a cin command to an argument in a while loop (C++)

I'm having trouble passing the reentered optionPackageCode after the nested while loop completes (cin >> optionPackageCode;) back to the first while loop so that it can check the conditions with the updated code. No clue what's wrong.
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
int main()
{
//Declaring variables
double basePrice = 0.0;
double subTotal = 0.0;
double associatedCosts = 0.0;
double finalPrice = 0.0;
int sub = 0;
int tries = 0;
string optionPackageCode = "";
//Populating arrays
string optionPackageCodeArray[5] = { "BB", "SP", "NP", "HE", "UC"};
string packageNameArray[5] = { "Base", "Sport", "Intermediate", "Luxury", "Custom"};
double packageCostArray[5] = { 1500.00,3250.00,4575.00,7500.00,5220.00 };
//Ask for input
cout << "Welcome! Please enter the base price and option package code for your vehicle!"
<< endl;
cout << fixed << setprecision(2);
cout << "Base Price: ";
cin >> basePrice;
cout << endl << "Option package code: ";
cin >> optionPackageCode;
//While loop
while (tries < 5 && optionPackageCodeArray[sub] != optionPackageCode)
{
tries += 1;
while (optionPackageCodeArray[sub] != optionPackageCode && sub < 5)
sub += 1;
//end while
cout << "Sorry, that code wasn't found in our database! Please try again: " << endl;
cin >> optionPackageCode;
} //end while
//Calculations and final output
if (optionPackageCodeArray[sub] == optionPackageCode)
{
subTotal = basePrice + packageCostArray[sub];
associatedCosts = subTotal * 0.15;
finalPrice = subTotal + associatedCosts;
cout << "The final cost for your vehicle with " << packageNameArray[sub] << " trim is $" << finalPrice << endl;
}
else
cout << "Sorry, you are out of tries...";
system("pause");
return 0;
}

C++ Program using functions

I'm writing a program for my C++ class I've complete the program. but it won't compile. I'm new to programming so I don't really know what I'm doing wrong. If there is anyone on here that can point me in the right direction. Please help me!
Prompt Description:
Write a C++ program to calculate free estimate for carpet and furniture cleaning of residential and business customers. The program continues until end of file is reached.
Fro residential customers, specify and update number of small couches ($50 each), large couches ($80 each), rooms ($70 each) and steps ($5 each) until exit is selected. the bill is calculated based on the number of items. If the amount is more than 500 dollars, a discount of 10% is applied to the bill. Then the customer is offered to select from an installment of 1,2,3, or 4 or press 0 to exit. Based on an installment option, the bill is increased slightlenter code herey, and each installment amount is calculated.
For business customers, ask the user to enter the amount of square footage and then the bill is calculated at .45 per square foot.
Here is the code:
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int exit = 0;
int smallcouches = 1;
int largecouches = 2;
int rooms = 3;
int steps = 4;
const float SMALL_COUCH = 50.0;
const float LARGE_COUCH = 80.0;
const float ROOMS = 70.0;
const float STEPS = 5.00;
const float PER_SQUARE_FOOT = 0.45f;
const float DISCOUNT_QUALIFIED = 500.0;
const float DISCOUNT = 0.10f;
const int ONE = 1;
const int TWO = 2;
const int THREE = 3;
const int FOUR = 4;
const float RATEONE = 0.0f;
const float RATETWO = 0.0535f;
const float RATETHREE = 0.055f;
const float RATEFOUR = 0.0575f;
float billAmount;
float ResidentialEstimate(float SMALL_COUCH, float LARGE_COUCH, float ROOMS, float STEPS, float DISCOUNT_QUALIFIED);
void GetResidentialItems(int& smallcouches, int& largecouches, int& rooms, int& steps);
void InstallmentPlan(float billAmount);
void BusinessEstimate(float PER_SQUARE_FOOT);
int main()
{
cout << fixed << showpoint << setprecision(2);
int customerType, residential_customer, business_customer;
char B, b, R, r;
residential_customer = R || r;
business_customer = B || b;
cout << "Enter customer type: R, r (Residential) or B, b (Business): ";
cin >> customerType; //Enter customer type
cout << endl;
while (cin) //While there is input to read
{
if (customerType == R || customerType == r) //if residential customer
{
ResidentialEstimate(SMALL_COUCH, LARGE_COUCH, ROOMS, STEPS, DISCOUNT_QUALIFIED); // call function ResidentialEstimate
InstallmentPlan(billAmount); // all function Installmentplan
}
else if (customerType == B || customerType == b) //else if business customer
{
BusinessEstimate(PER_SQUARE_FOOT); //call function BusinessEstimate
}
cout << "Enter customer type: R, r (Residential) or B, b (Business): ";
cin >> customerType; // Enter cutomer type
cout << endl;
}
return 0;
}
float ResidentialEstimate(float SMALL_COUCH, float LARGE_COUCH, float ROOMS, float STEPS, float DISCOUNT_QUALIFIED)
{
GetResidentialItems(smallcouches, largecouches, rooms, steps); //Call function GetResidentialItems to get items to clean
billAmount = (SMALL_COUCH + LARGE_COUCH + ROOMS + STEPS); //Calculate the bill amount
if (billAmount > 500) //if bill amount is more than 500 dollars
{
DISCOUNT_QUALIFIED = billAmount * 0.10f;
billAmount = billAmount - DISCOUNT_QUALIFIED; //Apply a discount of 10% to the bill amount
}
return billAmount; //return bill Amount
}
void GetResidentialItems(int& smallcouches, int& largecouches, int& rooms, int& steps)
{
int count;
int choice = smallcouches || largecouches || rooms || steps;
//Ask user to select an item to update or press 0 to exit
cout << "0. Exit, 1. Small Couches, 2. Large Couches, 3. Rooms, 4. Steps " << endl;
cout << "Enter one of the above choices: ";
cin >> choice;
cout << endl;
while (choice > 0) //while user hasn't pressed 0
{
choice = count;
cout << "Please enter the number of " << choice; //ask the user to enter a number from the item selected
cin >> count;
cout << endl;
//Show the current selections and numbers
cout << "Current selections: " << count << " Small Couches, " << count << " Large Couches, " << count << " Rooms, " << count << " Steps.";
//Ask user to select an item to update or press 0 to exit
choice = 0;
count = 0;
cout << "0. Exit, 1. Small Couches, 2. Large Couches, 3. Rooms, 4. Steps " << endl;
cout << "Enter one of the above choices: ";
cin >> choice;
cout << endl;
}
}
void InstallmentPlan(float billAmount)
{
int num;
int installment = 0;
int bill = 0;
//Ask user to select number of installments or 0 to exit
cout << "Please enter the desired number of instalments (1, 2, 3, or 4) or 0 to exit : ";
cin >> num;
cout << endl;
while (num > 0) //while user hasn't pressed 0
{
//calculate the installments
if (num == 1)
installment = billAmount;
else if (num == 2)
{
bill = billAmount * 0.0535f;
installment = bill / num;
}
else if (num == 3)
{
bill = billAmount * 0.055f;
installment = bill / num;
}
else if (num == 4)
{
bill = billAmount * 0.0575f;
installment = bill / num;
}
cout << "With " << num << " installment your bill of " << billAmount << " will be worth " << bill << "." << endl;
cout << "Each installment will be worth " << installment << endl;
//Ask user to select number of installments or 0 to exit
cout << "Please enter the desired number of instalments (1, 2, 3, or 4) or 0 to exit : ";
cin >> num;
cout << endl;
}
}
void BusinessEstimate(float squarefootage)
{
//Ask user for the square footage
cout << " Enter the approximate square footage: ";
cin >> squarefootage;
cout << endl;
//Calculate the bill amount
billAmount = squarefootage * PER_SQUARE_FOOT;
cout << "Your free Business Customer Estimate for " << squarefootage << "square footage = " << billAmount;
}

When using vector and arrary for multiple customer data it does not calculate correctly

When I run the program with either one or more customers. It seems to be that Only with the first customer data, the code I have does not do the calculations correctly for the first customer when trying to get the monthly payments and interest but the calculations are done correctly for the rest of the customers data inputted. What am I missing? Thank you.
#include <iostream>
#include <string>
#include <cmath>
#include <iomanip>
#include <vector>
using namespace std;
int main()
{
//Variables
vector <double> Loanlgth, Loanamt, interestRate;
vector <double> monthlyPay(100), loanTotal(100), creditScore(100), totalInterest;
char yes;
const int INPUT_CUSTOMER = 1, DISPLAY_LOAN = 2, EXIT_PROGRAM = 3;
vector <string> customerName;
int option;
int numCustomers = 0;
int index = 0;
//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) //Customer enters their information
{
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);
if (tempcreditScore <= 600)
tempinterestRate = .12;
interestRate.push_back(tempinterestRate);
if (tempcreditScore > 600)
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];
}
}
if (option == 2) // Displays 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;
}
} while (option != EXIT_PROGRAM);
system("pause");
return 0;
}
Currently, interestRate is populated wrongly. Initially, it contains a garbage value because it is not initialized and if the first condition is not true, the garbage value is pushed, otherwise .12. Next, if the second condition is true, .05 is pushed, otherwise the values from the above flow. So, these combinations of garbage and assigned values are causing values to be pushed twice.
Here's your code:
if (tempcreditScore <= 600)
tempinterestRate = .12;
interestRate.push_back(tempinterestRate);
if (tempcreditScore > 600)
tempinterestRate = .05;
interestRate.push_back(tempinterestRate);
You can correct this in a number of ways:
// push after the calculation is complete
if (tempcreditScore <= 600)
tempinterestRate = .12;
if (tempcreditScore > 600)
tempinterestRate = .05;
interestRate.push_back(tempinterestRate);
or, with if-else (preferable):
if (tempcreditScore <= 600)
tempinterestRate = .12;
else
tempinterestRate = .05;
interestRate.push_back(tempinterestRate);
or, with ternary operator ?: (conciseness and you can make it const):
const double tempinterestRate = (tempcreditScore <= 600 ? .12 : .05);
interestRate.push_back(tempinterestRate);
Apart from this, there are a number of points:
The naming convention is inconsistent throughout the code.
The variables must be initialized because the uninitialized ones may lead to Undefined Behavior.
In the absence of an aggregate type such as struct or class and with multiple pieces of information to store separately in vectors, it is better to keep all the push_backs exactly to once per iteration.
Magic numbers can be avoided for 600, .12 and .5.
The magic numbers for option comparison in if conditions can be removed with their proper constant equivalents i.e. INPUT_CUSTOMER and DISPLAY_LOAN. And, if-else can be used instead of if-if.
The scoping could be improved by moving the variables and objects closer to where they are used.
The vertical blank spaces can improve readability for relevant code blocks.
And, Why is "using namespace std;" considered bad practice?
There might be some other points that you can observe in the following updated code (live):
#include <iostream>
#include <string>
#include <iomanip>
#include <vector>
int main()
{
// Variables
std::vector<std::string> customerNames;
std::vector<double> loanLengths, loanAmounts, interestRates;
std::vector<double> monthlyPays, loanTotals, creditScores, totalInterests;
// Program
std::cout << "Thank you for choosing The Bank of UA for your loan requirements!\n\n";
const int INPUT_CUSTOMER = 1, DISPLAY_LOAN = 2, EXIT_PROGRAM = 3;
int option = EXIT_PROGRAM;
do
{
std::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: ";
std::cin >> option;
while (option < INPUT_CUSTOMER || option > EXIT_PROGRAM)
{
std::cout << "Please enter a valid menu option: ";
std::cin >> option;
}
if (option == INPUT_CUSTOMER) //Customer enters their information
{
int numCustomers = 0;
std::cout << "Please enter the number of customers you would like\n"
<< " to enter loan information for: ";
std::cin >> numCustomers;
for ( int index = 0; index < numCustomers; index++ )
{
std::string name;
double loanAmount = 0.0, loanLength = 0.0, creditScore = 0.0;
std::cout << "Please enter your name: ";
std::cin >> name;
customerNames.push_back( name );
std::cout << "Please enter the loan amount: $";
std::cin >> loanAmount;
loanAmounts.push_back( loanAmount );
std::cout << "Please enter the length of the loan in months: ";
std::cin >> loanLength;
loanLengths.push_back( loanLength );
std::cout << "What is your current credit score? ";
std::cin >> creditScore;
creditScores.push_back( creditScore );
double interestRate = 0.0;
if (creditScore <= 600)
interestRate = .12;
else
interestRate = .05;
// Ternary operator (?:) may also be used here
// const double interestRate = creditScore <= 600 ? .12 : .05;
interestRates.push_back(interestRate);
//Calculations
const double tempTotalInterest = loanAmounts[index] * interestRates[index];
totalInterests.push_back( tempTotalInterest );
const double tempTotalLoan = loanAmounts[index] + totalInterests[index];
loanTotals.push_back( tempTotalLoan );
const double tempMonthlyPay = loanTotals[index] / loanLengths[index];
monthlyPays.push_back( tempMonthlyPay );
}
}
else if (option == DISPLAY_LOAN) // Displays monthly payment
{
std::cout << std::fixed << std::setprecision(2);
for (int index = 0; index < customerNames.size(); index++)
{
std::cout << "\n---\n";
std::cout << customerNames[index] << " your total loan is " << loanTotals[index]
<< "\nwith a monthly payment of $" << monthlyPays[index]
<< "\nfor " << loanLengths[index] << " months with an interest"
<< "\nrate of " << interestRates[index] << std::endl;
std::cout << "---\n";
}
}
} while (option != EXIT_PROGRAM);
return 0;
}

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

Loop accepts first set of input and then reuses that value

I am currently learning C++ in school and one of our projects is to create a program to calculate a budget. When I run my program, the loop that accepts the input for item cost will take the input once and then reuse that value each time it loops back. I have already searched online for a solution and my teacher is just as confused about it as I am. It could be that there is a problem with Codeblocks but I have already tried it with a different editor. If anyone knows how I can fix it, that would be great.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
//Declares variables
float itemCount = 0;
float taxPercent = 0;
float itemCost = 0;
bool taxable = true;
float totalTaxable = 0;
float totalNontaxable = 0;
float total = 0;
//Receive user input
cout << "How many items to you have to buy: ";
cin >> itemCount;
cout << "\nWhat is the tax percentage (do not include the % sign): ";
cin >> taxPercent;
//This code runs once for every item
while (itemCount > 0){
//Receive the remaining user input
cout << "\nWhat is the cost of the item: ";
cin >> itemCost;
cout << "\nIs the item taxable (Please use either true or false): ";
cin >> taxable;
//Adds the item cost to either the taxable or nontaxable variables
if (taxable == true){
totalTaxable += itemCost;
cout << "true";
} else{
totalNontaxable += itemCost;
cout <<"false";
}
itemCount -= 1;
}
total = (totalTaxable * (1 + (taxPercent / 100))) + totalNontaxable;
cout << "\n--------------------------------------------------\n";
cout << "You must earn $";
cout << total;
cout << " to meet this budget\n\n";
}
As said in the comment, you can't use cin on boolean. From the doc :
The standard input stream is a source of characters determined by the environment.
So here's your fixed code (which will accept Y and nothing else) :
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
//Declares variables
float itemCount = 0;
float taxPercent = 0;
float itemCost = 0;
char taxable = '';
float totalTaxable = 0;
float totalNontaxable = 0;
float total = 0;
//Receive user input
cout << "How many items to you have to buy: ";
cin >> itemCount;
cout << "\nWhat is the tax percentage (do not include the % sign): ";
cin >> taxPercent;
//This code runs once for every item
while (itemCount > 0){
//Receive the remaining user input
cout << "\nWhat is the cost of the item: ";
cin >> itemCost;
cout << "\nIs the item taxable (Please use Y for Yes): ";
cin >> taxable;
//Adds the item cost to either the taxable or nontaxable variables
if (taxable == 'Y'){
totalTaxable += itemCost;
cout << "true";
} else{
totalNontaxable += itemCost;
cout <<"false";
}
itemCount -= 1;
}
total = (totalTaxable * (1 + (taxPercent / 100))) + totalNontaxable;
cout << "\n--------------------------------------------------\n";
cout << "You must earn $";
cout << total;
cout << " to meet this budget\n\n";
}