How to get a function to redelcare a variable in Main()? - c++

Im trying to do a paycheck calculator thing that takes out taxes, etc. after a gross income is inputted. I am using functions to calculate the each tax seperately, and then in my Main() I want to then subtract it all from the gross total to get the net pay. My problem is that I cannot figure out how to get the totals from the functions to subtract it in my main().
#include "stdafx.h"
#include <iostream>
#include <iomanip>
using namespace std;
double federalTax(double userInput, double total1) {
double total = total1;
total = userInput * 0.2;
cout << "Federal Tax: " << setw(12) << "-$" << total << endl;
total = total1;
return 0;
}
double stateTax(double userInput, double total2) {
double total = total2;
total = userInput * 0.04;
cout << "State Tax: " << setw(15) << "-$" << total << endl;
total = total2;
return 0;
}
double Medicare(double userInput, double total3) {
double total = total3;
total = userInput * 0.0275;
cout << "Medicare: " << setw(16) << "-$" << total << endl;
total = total3;
return 0;
}
double Pension(double userInput, double total4) {
double total;
total = userInput * 0.06;
cout << "Pension: " << setw(17) << "-$" << total << endl;
total4 = total;
return 0;
}
int main()
{
double userInput;
double total1 = 0, total2 = 0, total3 = 0, total4 = 0;
double sum;
cout << "What is your gross income?" << endl;
cin >> userInput;
cout << "Gross Income: " << setw(10) << "$" << userInput << endl;
federalTax(userInput, total1);
stateTax(userInput, total2);
Medicare(userInput, total3);
Pension(userInput, total4);
cout << "Health Insurance: " << setw(10) << "-$80" << endl;
sum = userInput - total1 - total2 - total3 - total4 - 80;
cout << "Net Pay: " << setw(15) << "$" << sum << endl;
system("pause");
return 0;
}
When I try to subtract it (which you can see with my declaration of double = sum) it is just taking the 0's for totals 1 through 4 that I initialized.

In such case you have to pass values by reference.By default, C++ does not accept values by reference.
#include "stdafx.h"
#include <iostream>
#include <iomanip>
using namespace std;
double federalTax(double userInput, double &total1) {
double total = total1;
total = userInput * 0.2;
cout << "Federal Tax: " << setw(12) << "-$" << total << endl;
total = total1;
return 0;
}
double stateTax(double userInput, double &total2) {
double total = total2;
total = userInput * 0.04;
cout << "State Tax: " << setw(15) << "-$" << total << endl;
total = total2;
return 0;
}
double Medicare(double userInput, double &total3) {
double total = total3;
total = userInput * 0.0275;
cout << "Medicare: " << setw(16) << "-$" << total << endl;
total = total3;
return 0;
}
double Pension(double userInput, double &total4) {
double total;
total = userInput * 0.06;
cout << "Pension: " << setw(17) << "-$" << total << endl;
total4 = total;
return 0;
}
int main()
{
double userInput;
double total1 = 0, total2 = 0, total3 = 0, total4 = 0;
double sum;
cout << "What is your gross income?" << endl;
cin >> userInput;
cout << "Gross Income: " << setw(10) << "$" << userInput << endl;
federalTax(userInput, total1);
stateTax(userInput, total2);
Medicare(userInput, total3);
Pension(userInput, total4);
cout << "Health Insurance: " << setw(10) << "-$80" << endl;
sum = userInput - total1 - total2 - total3 - total4 - 80;
cout << "Net Pay: " << setw(15) << "$" << sum << endl;
system("pause");
return 0;
}

Your issue is that you pass by valuenot by reference. So variables which are passed by value will be copied so that any change to those copied values within the function won't affect the original variable from main, or wherever. So changing total4 = total doesn't touch the total4 in main. Instead, try returning from the functions.
#include "stdafx.h"
#include <iostream>
#include <iomanip>
using namespace std;
double federalTax(double userInput) {
double total = 0;
total = userInput * 0.2;
cout << "Federal Tax: " << setw(12) << "-$" << total << endl;
return total;
}
double stateTax(double userInput) {
double total = 0;
total = userInput * 0.04;
cout << "State Tax: " << setw(15) << "-$" << total << endl;
return total;
}
double Medicare(double userInput) {
double total = 0;
total = userInput * 0.0275;
cout << "Medicare: " << setw(16) << "-$" << total << endl;
return total;
}
double Pension(double userInput) {
double total;
total = userInput * 0.06;
cout << "Pension: " << setw(17) << "-$" << total << endl;
return total;
}
int main()
{
double userInput;
double total1 = 0, total2 = 0, total3 = 0, total4 = 0;
double sum;
cout << "What is your gross income?" << endl;
cin >> userInput;
cout << "Gross Income: " << setw(10) << "$" << userInput << endl;
total1 = federalTax(userInput);
total2 = stateTax(userInput);
total3 = Medicare(userInput);
total4 = Pension(userInput);
cout << "Health Insurance: " << setw(10) << "-$80" << endl;
sum = userInput - total1 - total2 - total3 - total4 - 80;
cout << "Net Pay: " << setw(15) << "$" << sum << endl;
system("pause");
return 0;
}

Passing by value issues in creating new copies of the original parameters. On contrary to passing by reference or by pointer which means passing the very address of the original variables; which means any change affects the original one. Because no copy is created. The law of thumb Pass by reference as much as possible.
You can in your program to change it to look like reasonable:
1- Change the function to return void as long as you are not interested n the returned values.
2- Make the pass by reference.
3- Remove the local variables total_x in all the functions to affect the original ones.
One of the functions will look like this:
void federalTax(double &userInput, double& total1) {
total1 = userInput * 0.2;
cout << "Federal Tax: " << setw(12) << "-$" << total1 << endl;
}
Do the same for the remaining functions.

Related

How to create function for outputting year end balance and year end earned interest without monthly deposits?

I am trying to create a function that outputs year end balance and year end earned interest without monthly deposits. I am having a problem with fucntion reportWithoutMonthlyPay. With inputs 1 for investment, 50 for monthly deposit, %5 for annual interest, and 5 for years, it should output:
Year    Year End Balance     Year End Earned Interest
1         $1.05                        $0.05
2         $1.10                        $0.05
3         $1.16                        $0.06
4         $1.22                        $0.06
5         $1.28                        $0.06
Instead it is outputting:
1         $1.34                        $0.06
2         $1.80                        $0.07
3
        $2.42                        $0.10
4         $3.25                        $0.13
5         $4.36                        $0.18
Can someone help me with this?
Here is my code:
// BankingApp.cpp : This file contains the 'main' function. Program execution begins and
ends there.
//
#include <iostream>
#include <vector>
#include <iomanip>
using namespace std;
class Bank {
public:
void dataInput();
void displayInput();
void reportWithoutMonthlyPay();
void reportWithMonthlyPay();
private:
double investment;
double deposit;
int years;
double interest;
double monthly_interest;
double year_end_balance;
double year_end_interest;
vector<int> month_numbers;
vector<int> year_numbers;
};
void Bank::dataInput() {
cout << "Initial Investment Amount: " << endl;
cin >> investment;
cout << "Monthly Deposit: " << endl;
cin >> deposit;
cout << "Annual Interest: " << endl;
cin >> interest;
cout << "Number of years: " << endl;
cin >> years;
system("pause"); // Windows-specific command that tells platform to pause
program
cout << endl;
if (cin.get()) { // If any key is entered, displayInput function is called
displayInput();
}
}
void Bank::displayInput() {
cout << "Initial Investment Amount: " << "$" << investment << endl;
cout << "Monthly Deposit: " << "$" << deposit << endl;
cout << "Annual Interest: " << interest << "%" << endl;
cout << "Number of years: " << years << endl;
system("pause");
cout << endl;
reportWithoutMonthlyPay();
}
void Bank::reportWithoutMonthlyPay() {
year_numbers.resize(years);
month_numbers.resize(12);
interest = interest / 100;
year_end_interest = 0;
year_end_balance = investment;
cout << " Balance and Interest Without Additional Monthly Deposit " << endl;
cout << "=============================================================" << endl;
cout << "Year Year End Balance Year End Earned Interest" << endl;
cout << "-------------------------------------------------------------" << endl;
for (int i = 0; i < year_numbers.size(); i++) {
year_numbers[i] = i + 1;
year_end_interest = 0;
for (int j = 0; j < month_numbers.size(); j++) {
monthly_interest = year_end_balance * (interest / (double)12);
year_end_interest += monthly_interest;
year_end_balance += year_end_interest;
month_numbers[j]++;
}
cout << year_numbers[i] << " $" << fixed << setprecision(2) <<
year_end_balance << " $" << year_end_interest << endl;
year_numbers[i]++;
}
cout << endl;
system("pause");
reportWithMonthlyPay();
}
void Bank::reportWithMonthlyPay() {
year_numbers.resize(years);
month_numbers.resize(12);
year_end_interest = 0;
year_end_balance = investment;
cout << " Balance and Interest With Additional Monthly Deposit " << endl;
cout << "==========================================================" << endl;
cout << "Year Year End Balance Year End Earned Interest" << endl;
cout << "----------------------------------------------------------" << endl;
for (int i = 0; i < year_numbers.size(); i++) {
year_numbers[i] = i + 1;
year_end_interest = 0;
for (int j = 0; j < month_numbers.size(); j++) {
year_end_balance += deposit;
monthly_interest = year_end_balance * (interest / (double)12);
year_end_balance += monthly_interest;
year_end_interest += monthly_interest;
month_numbers[j]++;
}
cout << year_numbers[i] << " $" << fixed << setprecision(2) <<
year_end_balance << " $" << year_end_interest << endl;
year_numbers[i]++;
}
}
int main()
{
Bank userInput;
userInput.dataInput();
}

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

Why is the calculation in the subtotal of this program incorrect?

I am trying to create a C++ program that calculates sales tax for a customer and displays a receipt. For example, if you entered 10 as the first sale amount and the tax rate is 0.0825 it should display the total tax as $0.83. Why does my subtotal and total due at the end of the receipt display $10.82 when it should be $10.83?
//Customer Receipt
#include <iostream>
#include <iomanip>
#include <vector>
using namespace std;
struct Item_Receipt
{
double item;
double cost;
double tax;
double subtotal;
};
int main()
{
vector <Item_Receipt> Store_Receipt;
Item_Receipt Purchase;
//Variables
const double item_tax = .0825;
double Item_Total = 0.0;
double Tax_Total = 0.0;
double Total_Sales = 0.0;
int numSales = 0;
cout << "First sales amount (Enter a 0 to stop): ";
cin >> Purchase.item;
Purchase.tax = Purchase.item * item_tax;
Purchase.subtotal = Purchase.item + Purchase.tax;
Store_Receipt.push_back(Purchase);
Item_Total += Purchase.item;
Tax_Total += Purchase.tax;
Total_Sales += Purchase.subtotal;
numSales++;
while (Purchase.item > 0.0)
{
cout << "Next sales amount (Enter a 0 to stop): ";
cin >> Purchase.item;
if(Purchase.item > 0.0)
{
Purchase.tax = Purchase.item * item_tax;
Purchase.subtotal = Purchase.item + Purchase.tax;
Store_Receipt.push_back(Purchase);
Item_Total += Purchase.item;
Tax_Total += Purchase.tax;
Total_Sales += Purchase.subtotal;
numSales++;
}
else
cout << endl << "That was the last item being puchased.\nHere is your itemized receipt." << endl << endl;
}
//end while
//Output
cout << "----------------------------------------- " << endl;
cout << "\tReceipt of Purchase" << endl;
cout << "----------------------------------------- " << endl << endl;
cout << fixed << setprecision(2);
cout << setw(10) << "Item Cost" <<
setw(15) << "Item Tax" <<
setw(15) << "Subtotal" << '\n';
cout << "----------------------------------------- " << endl;
for(int x=0;x<numSales;x++)
cout << setw(8) << Store_Receipt[x].item << setw(15) << Store_Receipt[x].tax <<
setw(15) << Store_Receipt[x].subtotal << endl;
cout << "----------------------------------------- " << endl;
cout << setw(10) << "Item Total" <<
setw(15) << "Tax Total" <<
setw(15) << "Total Due" << endl;
cout << setw(8) << Item_Total << setw(15) << Tax_Total <<
setw(15) << Total_Sales << endl;
cout << "----------------------------------------- " << endl;
cout << "\tYou purchased " << numSales << " items." << endl;
cout << "----------------------------------------- " << endl;
cout << "\tThank you! Have a nice day!" << endl;
cout << "----------------------------------------- " << endl;
cin >> numSales;
return 0;
}
setprecision(2) doesn't mean "round to 2 decimal digits," it means "display 2 decimal digits." The actual value is 10.825 but you're only displaying the first two decimal digits.
If you want to round away from the midpoint, you need to use one of the rounding functions on the result.
Since you want to round to the second decimal place, you have to first multiply the number by 100, then round it, then divide by 100. You could do this with the help of a function:
double round_to_cents(double v) {
return std::round(v * 100) / 100;
}
Then round the tax calculation:
Purchase.tax = round_to_cents(Purchase.item * item_tax);
(Demo)

Attempting to loop back to the beginning to run my program again

I am currently writing a code where in my main function I am just calling other functions. I am attempting to reloop back to the begining so the user can run the program again. The main function is just to call functions so my question is I know it is not possible to go back to the main function, but is it possible to create a function that will loop all other functions again? I feel as though I tried everything and continue to get infinite loops. I attached my code.
To condense the code please understand that all variables/classes are declared
void instructions();
void full_outputs(string, double, double, double);
int main()
{
instructions();
employee_num = employee_ID();
//cout << employee_num << " This is the employee ID."<<endl;
base_salary = baseSalary();
//cout << base_salary << " This is the employee's base salary." <<endl;
per_commission = percentage_commission();
//cout << per_commission << " This is the employee's percentage commission." << endl;
base_commission = base_and_com(base_salary, per_commission);
cout<< base_commission << "This is the total base salary with comission" << endl;
gross_pay = grossPay(base_commission);
//cout << gross_pay << "This is the gross pay"<<endl;
state_tax_hold = stateTax_hold(gross_pay);
//cout<< state_tax_hold << "This is the state tax hold on the amount" <<endl;
fica_total = ficaTotal(gross_pay);
//cout << fica_total << " This is the fica hold on the amount" <<endl;
fed_tax = fedTax(gross_pay);
//cout << fed_tax << " THis is the federal tax hold on the amount" << endl;
total_tax_hold = withholding_total(state_tax_hold, fica_total, fed_tax);
//cout << total_tax_hold << " This is the total tax withholding" << endl;
net_pay = netPay(total_tax_hold, gross_pay);
//cout << net_pay << " This is the total net pay" << endl;
full_outputs(employee_num, gross_pay, total_tax_hold, net_pay);
return 0;
}
void instructions()
{
cout << " This program will process sales employee's base salary \n";
cout << " and their percentage commission. \n";
cout << " You will be prompted to enter the employee's ID, base salary \n";
cout << " and percentage commission. \n";
cout << " \n";
cout << " The program will terminate if unspecified characters are used. \n";
}
string employee_ID()
{
string employee_num;
cout << " Please enter the employees eight digit ID number" << endl;
cin >> employee_num;
return employee_num;
}
double baseSalary()
{
double base_salary;
cout << " Please enter the employees base salary " << endl;
cin >> base_salary;
return base_salary;
}
float percentage_commission()
{
float per_commission;
cout << " Please enter the employees percentage commission."<< endl;
cout << " Please do not enter the percent symbol." << endl;
cout << " Percentage commission is between 0.05% - 10%" << endl;
cin >> per_commission;
while ((per_commission < 0.05)||(per_commission > 10))
{
cout << "The commission rate is not between 0.05% and 10%" << endl;
cout << "Please try again " << endl;
cin >> per_commission;
}
per_commission = per_commission / PERCENT_TO_DECIMAL;
return per_commission;
}
double base_and_com(double base_salary, float per_commission)
{
double base_commission;
double total;
total = base_salary*per_commission;
base_commission = total + base_salary;
return base_commission;
}
double grossPay(double base_commission)
{
double gross_pay;
gross_pay = base_commission;
cout << fixed << showpoint << setprecision(2);
return gross_pay;
}
double stateTax_hold(double gross_pay)
{
double state_tax_hold;
state_tax_hold= gross_pay*STATE_TAX;
return state_tax_hold;
}
double ficaTotal (double gross_pay)
{
double fica_total;
fica_total = gross_pay* FICA;
return fica_total;
}
double fedTax (double gross_pay)
{
double fed_tax;
if (gross_pay <= 500)
{
fed_tax = gross_pay * FEDERAL_TAX_UNDER;
}
else
{
fed_tax = gross_pay * FEDERAL_TAX_OVER;
}
return fed_tax;
}
double withholding_total(double fed_tax, double fica_total, double state_tax_hold )
{
double tax_withholding_total;
tax_withholding_total = fed_tax + fica_total + state_tax_hold;
cout << fixed << showpoint << setprecision(2);
return tax_withholding_total;
}
double netPay(double total_tax_hold, double gross_pay)
{
double net_pay;
net_pay = (gross_pay - total_tax_hold);
cout << fixed << showpoint << setprecision(2);
return net_pay;
}
void full_outputs(string employee_num, double gross_pay, double total_tax_hold, double net_pay)
{
cout << " The employee ID : " << right << employee_num << endl;
cout << " The gross pay is: " << right << gross_pay << endl;
cout << " The total tax withholding amount is : " << right << total_tax_hold << endl;
cout << " The net pay is: " << right << net_pay << endl;
}
As you know, in main you can just have a while loop with the code you want to repeat inside it:
int main()
{
// this will loop forever, until you explicitly break or return
while (true) {
// your code here
}
}
... but since you are constrained by the artificial limitation of only having function calls in main...
void run()
{
// this will loop forever, until you explicitly break or return
while (true) {
// your code here
}
}
int main()
{
run();
}

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.