Code WORKS Math DOESN'T - c++

My code compiles nicely, but the math formulas that I am using aren't providing the right outcome. I need to calculate the balance, withdrawn, and interest for all 3 months. I am also required to validate user's input. For these purposes I am using nested loops. Please let me know if you spot my mistake. Thank you lovely people!
cout << "Please enter the starting balance: ";
cin >> startBalance;
cout << "Please enter the annual interest rate: ";
cin >> annualInterest;
for (int month = 1; month <= 3; month++) {
do {
cout << setprecision(5);
cout << "Please enter the total amount deposited on month " << month << ": ";
cin >> balance;
if (balance <0) {
goodChoice = false;
cout << "\n\t***ERROR " << balance << " ***";
cout << "*** Choice must be positive***\n" << endl;
}
else {
goodChoice = true;
}
startBalance += balance; //need to calculate the balance for all 3 months
} while (!goodChoice);
do {
cout << setprecision(5);
cout << "Please enter the total amount withdrawn on " << month << ": ";
cin >> withdrawn;
if ( (withdrawn <0) || (withdrawn > startBalance) ) {
goodChoice = false;
cout << "***ERROR " << withdrawn << " ***";
cout << "*** Choice must be positive or greater than the balance***" << endl;
}
else {
goodChoice = true;
}
finalWithdrawn += withdrawn; // the total amount of withdrawn
finalBalance = startBalance - withdrawn;
monthInterest = ((startBalance + finalBalance) / 2) * (annualInterest / 12);
totalInterest += monthInterest; //total interest for all 3 months
endBalance = monthInterest + finalBalance;
} while (!goodChoice);
}
cout << "Total Deposit: " << endBalance << endl;
cout << "Total Withdrawn: " << finalWithdrawn << endl;
cout << "Total Interest: " << totalInterest << endl;
cout << "Final Balance: " << endBalance << endl;

You have a lot of extra variables defined which aren't needed. Also, your interest rate may have been in percentage instead of a decimal number, i.e. 10% = 0.1. Also, your monthInterest is taking an average then applying interest. I wrote this up and it seems to work.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
float totalDeposit = 0.0f;
float totalWithdrawn = 0.0f;
float totalInterest = 0.0f;
float totalBalance = 0.0f;
float interestRate = 0.0f;
setprecision(5); //?
cout << "Enter starting balance: ";
cin >> totalBalance;
cout << "Enter annual interest rate (%): ";
cin >> interestRate;
// Convert to monthly and non-percent; i.e. 10% = 0.1 = 10 / 100
interestRate = interestRate / 100.0f / 12.0f;
for (int month = 1; month <= 3; month++)
{
float deposit = -1.0; // Default to an error state
while (deposit < 0.0)
{
cout << "Enter total deposited in month " << month << ": ";
cin >> deposit;
if (deposit < 0.0f)
{
cout << "ERROR: Invalid amount" << endl;
continue;
}
}
float withdrawn = -1.0f; // Default to an error state
while (withdrawn < 0.0f)
{
cout << "Enter total withdrawn in month " << month << ": ";
cin >> withdrawn;
if (withdrawn < 0.0f)
{
cout << "ERROR: Invalid amount" << endl;
continue;
}
}
totalDeposit += deposit;
totalWithdrawn += withdrawn;
totalBalance = totalBalance + deposit - withdrawn;
totalBalance += totalBalance * interestRate;
totalInterest += totalBalance * interestRate;
}
cout << "Total Deposit: " << totalDeposit << endl;
cout << "Total Withdrawn: " << totalWithdrawn << endl;
cout << "Total Interest: " << totalInterest << endl;
cout << "Final Balance: " << totalBalance << endl;
int wait; // Pause so console window doesn't close. Delete this line.
cin >> wait;
return 0;
}

Related

How to update a while loop with multiple if statements?

I am working on the "checkout" process of my vending machine code. I want to write it so that the program will keep asking for the amount needed from the user until all the money is entered. However, this code segment does not completely work.
"Checkout" Segment of Code:
while (money < total) {
float amountOwed = total - money;
cout << "Please insert another $" << amountOwed << endl;
cout << "Enter amount: $" << flush;
float payment;
cin >> payment;
}
if (money > total) {
float change = money - total;
cout << "Thank you! You have $" << change << " change." << endl;
}
if (money == total) {
cout << "Thank you! Have a nice day!." << endl;
}
Full code below:
#include <iostream>
#include <iomanip>
using namespace std;
string menuItems[5] = { "Popcorn", "Coconut Clusters" , "Granola Bar" , "Trail Mix" , "Chocolate" };
float cost[5] = { 2, 3, 2.50, 1.50, 1 };
void vendingMachine() {
for (int i = 0; i < 5; i++)
cout << i + 1 << ". " << menuItems[i] << ": $" << cost[i] << endl;
}
int main() {
cout.precision(2);
cout << std::fixed;
cout << "Vending Machine" << endl;
cout << "----Items------" << endl;
vendingMachine();
cout << "Enter 0 to checkout" << endl;
float total;
total = 0;
int item;
do {
cout << "Enter your selection: " << flush;
cin >> item;
item = item - 1;
//here will be printed : $0 has been added to cart even if you pressed 0 and what to escape
//is it possible to fix this??
cout << menuItems[item] << ": $" << cost[item] << " has been added to cart." << endl;
total = total + cost[item];
} while (item != -1);
cout << " " << endl;
cout << "Proceding to checkout..." << endl;
cout << "========================" << endl;
cout << "Amount due: $" << total << endl;
cout << "Insert money here: $" << flush;
float money;
cin >> money;
while (money < total) {
float amountOwed = total - money;
cout << "Please insert another $" << amountOwed << endl;
cout << "Enter amount: $" << flush;
float payment;
cin >> payment;
}
if (money > total) {
float change = money - total;
cout << "Thank you! You have $" << change << " change." << endl;
}
if (money == total) {
cout << "Thank you! Have a nice day!." << endl;
}
return 0;
}
In this loop:
while (money < total) {
you are not modifying money or total so the loop will never exit.
You probably want to update money like this:
while (money < total) {
// ...
cin >> payment;
money += payment;
}

How to repeat the whole process for another customer until user stop the program?

When the user enters is prompt with the "Continue with another customer (Y/N)?" They should be asked to press Y to repeat the program with a different customer, or N to end the program entirely. I'm not sure where to put the do-while statement in the code for. I have tried to put if statments, that doesnt work. When doing the do while statements the "Welcome to pizza world" text comes up, but it does not repeat the code, it will just end the program normally.
#include <iostream>
using namespace std;
int main() {
int pizzas, drinks;
char drink_type, more;
double order = 0.0;
int count = 0, total_sodas = 0, total_milkshake = 0, total_pizzas = 0;
//This will set the precision of the decimal output 2 decimal places.
cout.setf(ios::showpoint);
cout.precision(2);
cout.setf(ios::fixed);
cout << "Welcome to Pizza World" << endl;
do{
count++;
cout << "\n\nHow many pizzas would you like?";
cin >> pizzas;
while (pizzas < 0)
{
cout << "That's an invalid number of pizzas.Try again:";
cin >> pizzas;
}
cout << "How many drinks would you like?";
cin >> drinks;
while (drinks < 0)
{
cout << "That's an invalid number of drinks.Try again:";
cin >> drinks;
}
if (drinks > 0) {
cout << "You chose to order " << drinks << " drinks. Enter 'S' for soda and 'M' for milkshake:";
cin >> drink_type;
switch (drink_type)
{
case 'S':
case 's':
order = order + 1.95 * drinks;
total_sodas = total_sodas + drinks;
break;
case 'M':
case 'm':
order = order + 4.25 * drinks;
total_milkshake = total_milkshake + drinks;
break;
}
}
order = order + 12.49 * pizzas;
total_pizzas = total_pizzas + pizzas;
order = order + 0.06 * order;
cout << "\n\nThe current order total including tax is $" << order << endl << endl;
cout << "Would you like to place another order(Y/N)?";
cin >> more;
// Resetting the order.
order = 0.0;
}while (more == 'Y' || more == 'y');
double subtotal = 0.0, tax;
cout << "\n##########################" << endl;
cout << "Your itemized bill for " << count << " orders:" << endl;
// Showing the calculations of every item only if its count is more than zero
if (total_pizzas > 0)
{
subtotal = subtotal + total_pizzas * 12.49;
cout << "Pizzas: " << total_pizzas << " x $12.49 = $" << total_pizzas * 12.49 << endl;
}
if (total_sodas > 0)
{
subtotal = subtotal + total_sodas * 1.95;
cout << "Sodas: " << total_sodas << " x $1.95 = $" << total_sodas * 1.95 << endl;
}
if (total_milkshake > 0)
{
subtotal = subtotal + total_milkshake * 4.25;
cout << "Sodas: " << total_milkshake << " x $4.25 = $" << total_milkshake * 4.25 << endl;
}
cout << "-------------------------------" << endl;
cout << "Subtotal = $" << subtotal << endl;
tax = subtotal * 0.06;
cout << "Tax = $" << tax << endl;
cout << "Total = $" << (subtotal + tax) << endl;
do {
cout << "Continue with another customer (Y/N)? \n";
cin >> more;
cout << "Welcome to Pizza World" << endl;
if (more == 'Y' || more == 'y')break;
} while (1);
system("pause");
return 0;
}
#include <iostream>
using namespace std;
int main() {
int pizzas, drinks;
char drink_type, more;
double order = 0.0;
int count = 0, total_sodas = 0, total_milkshake = 0, total_pizzas = 0;
//This will set the precision of the decimal output 2 decimal places.
cout.setf(ios::showpoint);
cout.precision(2);
cout.setf(ios::fixed);
cout << "Welcome to Pizza World" << endl;
int ch=1;
while(ch){
do{
count++;
cout << "\n\nHow many pizzas would you like?";
cin >> pizzas;
while (pizzas < 0)
{
cout << "That's an invalid number of pizzas.Try again:";
cin >> pizzas;
}
cout << "How many drinks would you like?";
cin >> drinks;
while (drinks < 0)
{
cout << "That's an invalid number of drinks.Try again:";
cin >> drinks;
}
if (drinks > 0) {
cout << "You chose to order " << drinks << " drinks. Enter 'S' for soda and 'M' for milkshake:";
cin >> drink_type;
switch (drink_type)
{
case 'S':
case 's':
order = order + 1.95 * drinks;
total_sodas = total_sodas + drinks;
break;
case 'M':
case 'm':
order = order + 4.25 * drinks;
total_milkshake = total_milkshake + drinks;
break;
}
}
order = order + 12.49 * pizzas;
total_pizzas = total_pizzas + pizzas;
order = order + 0.06 * order;
cout << "\n\nThe current order total including tax is $" << order << endl << endl;
cout << "Would you like to place another order(Y/N)?";
cin >> more;
// Resetting the order.
order = 0.0;
}while (more == 'Y' || more == 'y');
double subtotal = 0.0, tax;
cout << "\n##########################" << endl;
cout << "Your itemized bill for " << count << " orders:" << endl;
// Showing the calculations of every item only if its count is more than zero
if (total_pizzas > 0)
{
subtotal = subtotal + total_pizzas * 12.49;
cout << "Pizzas: " << total_pizzas << " x $12.49 = $" << total_pizzas * 12.49 << endl;
}
if (total_sodas > 0)
{
subtotal = subtotal + total_sodas * 1.95;
cout << "Sodas: " << total_sodas << " x $1.95 = $" << total_sodas * 1.95 << endl;
}
if (total_milkshake > 0)
{
subtotal = subtotal + total_milkshake * 4.25;
cout << "Sodas: " << total_milkshake << " x $4.25 = $" << total_milkshake * 4.25 << endl;
}
cout << "-------------------------------" << endl;
cout << "Subtotal = $" << subtotal << endl;
tax = subtotal * 0.06;
cout << "Tax = $" << tax << endl;
cout << "Total = $" << (subtotal + tax) << endl;
cout << "Continue with another customer (1/0)? \n";
cin >> ch;
}
system("pause");
return 0;
}
Ive actually removed this piece of code:
do {
cout << "Continue with another customer (Y/N)? \n";
cin >> more;
cout << "Welcome to Pizza World" << endl;
if (more == 'Y' || more == 'y')break;
} while (1);
and placed the entire do while loop inside a while that prompts if you want to continue to next customer.

How do I get the month to stop displaying 1.00, 2.00, ... etc

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.

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.

Calculations no processing C++

I'm making a simple payroll calculator and for some reason my "taxes" aren't calculating. When I run the program they just show $0 in the output. Any idea whats causing this? I commented "// Not calculating. Shows $0" on the lines that aren't calculating.
#include <iostream>
using namespace std;
int main()
// Parameters: None
// Returns: Zero
// Calls: None
{
int const hourly_wage = 16.78, overtime_rate = 25.17, social_security = 0.06, federal_income = 0.14, state_income = 0.05, union_dues = 10;
int gross_pay, hours_worked, number_of_dependents, ss_withheld, federal_withheld, state_withheld, net_pay, insurance, overtime_pay, again;
cout << "This program will calculate payroll for an employee." << endl;
do
{
cout << "\n\nEnter the number of hours the employee worked: " << endl;
cin >> hours_worked;
if (hours_worked > 40) {
overtime_pay = (hours_worked - 40) * overtime_rate;
gross_pay = (40 * hourly_wage) + overtime_pay;
}
else {
gross_pay = hours_worked * hourly_wage;
}
cout << "\n\nEnter the number of dependents for employee: " << endl;
cin >> number_of_dependents;
if (number_of_dependents >= 3) {
insurance = 35;
}
else {
insurance = 0;
}
// Payroll Calculation
ss_withheld = gross_pay * social_security;
federal_withheld = gross_pay * federal_income;
state_withheld = gross_pay * state_income;
net_pay = gross_pay - (ss_withheld + federal_withheld + state_withheld + insurance + union_dues);
cout << "\n\nGross Pay: $" << gross_pay << endl;
cout << "Social Security Withhholding: $" << ss_withheld << endl; // Not calculating. Shows $0
cout << "Federal Withholding: $" << federal_withheld << endl; // Not calculating. Shows $0
cout << "State Withholding: $" << state_withheld << endl; // Not calculating. Shows $0
cout << "Union Dues: $" << union_dues << endl;
cout << "Insurance Deduction: $" << insurance << endl;
cout << "Net Pay: $" << net_pay << endl;
cout << "\nDo you want to do another employee(Y/N)? ";
cin >> again;
} while (again == 'y' || again == 'Y');
cout << "\nHope they enjoy the money!" << endl;
return 0;
}
It looks like you are creating int Const for double values. ie.
#include "stdafx.h";
#include <iostream>
using namespace std;
int main()
// Parameters: None
// Returns: Zero
// Calls: None
{
int const union_dues = 10;
double const hourly_wage = 16.78, overtime_rate = 25.17, social_security = 0.06, federal_income = 0.14, state_income = 0.05;
double gross_pay, hours_worked, number_of_dependents, ss_withheld, federal_withheld, state_withheld, net_pay, insurance, overtime_pay, again;
cout << "This program will calculate payroll for an employee." << endl;
do {
cout << "\n\nEnter the number of hours the employee worked: " << endl;
cin >> hours_worked;
if (hours_worked > 40) {
overtime_pay = (hours_worked - 40) * overtime_rate;
gross_pay = (40 * hourly_wage) + overtime_pay;
}
else {
gross_pay = hours_worked * hourly_wage;
}
cout << "\n\nEnter the number of dependents for employee: " << endl;
cin >> number_of_dependents;
if (number_of_dependents >= 3) {
insurance = 35;
}
else {
insurance = 0;
}
// Payroll Calculation
ss_withheld = gross_pay * social_security;
federal_withheld = gross_pay * federal_income;
state_withheld = gross_pay * state_income;
net_pay = gross_pay - (ss_withheld + federal_withheld + state_withheld + insurance + union_dues);
cout << "\n\nGross Pay: $" << gross_pay << endl;
cout << "Social Security Withhholding: $" << ss_withheld << endl; // Not calculating. Shows $0
cout << "Federal Withholding: $" << federal_withheld << endl; // Not calculating. Shows $0
cout << "State Withholding: $" << state_withheld << endl; // Not calculating. Shows $0
cout << "Union Dues: $" << union_dues << endl;
cout << "Insurance Deduction: $" << insurance << endl;
cout << "Net Pay: $" << net_pay << endl;
cout << "\nDo you want to do another employee(Y/N)? ";
cin >> again;
} while (again == 'y' || again == 'Y');
cout << "\nHope they enjoy the money!" << endl;
return 0;
}