Attempting to loop back to the beginning to run my program again - c++

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

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

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)

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

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.

Comparing Cell Phone plans c++

I'm new here. Sorry if I'm not posting correctly. My program is comparing cell phone plans based on minutes. I want to know how I can compare plans to determine the best plan for the money. I believe I should be using minimum functions for this, but I'm honestly stuck. My code is below. Is it possible to find the minimum value from 3 separate functions? I'm not looking for an answer, but maybe an example or an article how to do so. Thanks!
#include<iostream>
using namespace std;
void companyA();
void companyB();
void CompanyC();
int min(); // I want to use this to find my minimum
int numEmployees;
int avgMin;
double totalCost;
// double bestChoice; Not used yet
int main()
{
double newMin;
cout << "Please enter number of employees." << endl;
cin >> numEmployees;
cout << "Please enter average minutes used by each employee. " << endl;
cin >> avgMin;
if (numEmployees < 0)
{
cout << "Incorrect value. Please enter positive number of employees." << endl;
cin >> numEmployees;
}
else if (avgMin < 0)
{
cout << "Incorrect value. Please enter positive number of minutes. " << endl;
cin >> avgMin;
}
cout << "\nStandard Packages" << endl;
cout << "Company A: For $29.99 per month, 450 minutes are included. Additional minutes are $0.35 per minute." << endl;
cout << "Company B: For $49.99 per month, 900 minutes are provided. Additional minutes are $0.30 per minute." << endl;
cout << "Company C: For $59.99 per month, unlimited minutes are provided." << endl;
companyA();
companyB();
companyC();
cout << "\nBased on the number of employees and average minutes used, " << x << "is the best choice." << endl;
system("pause");
return 0;
}
void companyA()
{
if (avgMin <= 450)
{
totalCost = 29.99*numEmployees;
cout << "\nCompany A will cost an $" << totalCost << " a month for " << numEmployees << " employee(s)." << endl;
}
else if (avgMin > 450)
{
totalCost = (avgMin-450)*0.35+29.99;
cout << "\nCompany A will cost an $" << totalCost << " a month for " << numEmployees << " employee(s)." << endl;
}
}
void companyB()
{
if (avgMin <= 900)
{
totalCost = 49.99*numEmployees;
cout << "Company B will cost an $" << totalCost << " a month for " << numEmployees << " employee(s)." << endl;
}
else if (avgMin > 900)
{
totalCost = (avgMin - 900)*0.30 + 49.99;
cout << "Company B will cost an $" << totalCost << " a month for " << numEmployees << " employee(s)." << endl;
}
}
void companyC()
{
totalCost = 59.99*numEmployees;
cout << "Company C will cost an $" << totalCost << " a month for " << numEmployees << " employee(s)." << endl;
}
I don't know if this is what you're looking for.
void minimum(double numEmployees, double avgMin);
double minimumCompany(double x, double y, double z);
void minimum(double numEmployees, double avgMin)
{
double totalCostA, totalCostB, totalCostC, minimumTotal;
string choice;
if (avgMin <= 450)
{
totalCostA = 29.99 * numEmployees;
cout << "\nCompany A will cost an $" << totalCostA << " a month for " << numEmployees << " employee(s)." << endl;
}
else if (avgMin > 450)
{
totalCostA = (avgMin - 450) * 0.35 + 29.99;
cout << "\nCompany A will cost an $" << totalCostA << " a month for " << numEmployees << " employee(s)." << endl;
}
if (avgMin <= 900)
{
totalCostB = 49.99*numEmployees;
cout << "Company B will cost an $" << totalCostB << " a month for " << numEmployees << " employee(s)." << endl;
}
else if (avgMin > 900)
{
totalCostB = (avgMin - 900)*0.30 + 49.99;
cout << "Company B will cost an $" << totalCostB << " a month for " << numEmployees << " employee(s)." << endl;
}
totalCostC = 59.99*numEmployees;
cout << "Company C will cost an $" << totalCostC << " a month for " << numEmployees << " employee(s)." << endl;
minimumTotal = minimumCompany(totalCostA, totalCostB, totalCostC);
if (minimumTotal == totalCostA)
{
choice = "Company A";
}
else if (minimumTotal == totalCostB)
{
choice = "Company B";
}
else
{
choice = "Company C";
}
cout << "\nBased on the number of employees and average minutes used, " << choice << " is the best choice." << endl;
}
double minimumCompany(double x, double y, double z)
{
double minimum = x;
if (y < minimum ) {
minimum = y;
}
if (z < minimum) {
minimum = z;
}
return minimum;
}
int main()
{
double numEmps, averageMin;
bool isValid = true;
while (isValid)
{
cout << "Please enter number of employees." << endl;
cin >> numEmps;
cout << "Please enter average minutes used by each employee. " << endl;
cin >> averageMin;
if ((numEmps < 0))
{
cout << "Please enter number of employees. " << endl;
cin >> numEmps;
isValid = true;
}
else
{
isValid = false;
}
if ((averageMin < 0))
{
cout << "Please enter average minutes used by each employee. " << endl;
cin >> numEmps;
isValid = true;
}
else
{
isValid = false;
}
}
cout << "\nStandard Packages" << endl;
cout << "Company A: For $29.99 per month, 450 minutes are included. Additional minutes are $0.35 per minute." << endl;
cout << "Company B: For $49.99 per month, 900 minutes are provided. Additional minutes are $0.30 per minute." << endl;
cout << "Company C: For $59.99 per month, unlimited minutes are provided." << endl;
minimum(numEmps, averageMin);
system("pause");
return 0;
}

How do I pass data through multiple functions and call them correctly in main?

I'm trying to call userWeight into the double convert() function. How do I do this? I'm running into issues with it no cooperating in main.
#include <iostream>
#include <string>
using namespace std;
// health calc
string name()
{
cout << "Welcome ________ ... uhmmmm, what was your name again? ";
string name1;
cin >> name1;
cout << " " << endl;
cout << " Oh that's right! Your name was " << name1 << ", how could I forget that?!" << endl;
return name1;
}
int height(string name1) //(string name1) is what we are passing into this function
{
//feet and inches to inches
cout << " How tall are you, " << name1 <<"?"<< endl;
cout << " " << endl;
cout << " " << endl;
cout << " Enter feet: ";
int feet;
cin >> feet;
cout << " " << endl;
cout << " Enter inches: ";
int inches;
cin >> inches;
int inchesheight;
inchesheight = (feet * 12) + inches;
cout << " " << endl;
cout << " Your height is equal to " << inchesheight << " inches total." << endl;
if (inchesheight < 65 )
{
cout << " You are shorter than the average male." << endl;
}
else if (inchesheight > 66 && inchesheight < 72)
{
cout << " You are of average height." << endl;
}
else
{
cout << " You are taller than average." << endl;
}
}
double wieght()
{
cout << " How much do you weigh? (In pounds) " << endl;
double userWeight;
cin >> userWeight;
cout << " Ok so your weight in the Imperial System (lbs.), is " << userWeight << endl;
cout << " Would you like to know what your weight is in the Metric System? (kilograms) " << endl;
cout << " please answer as 'yes' or 'no;" << endl;
string response;
cin >> response;
if (response == "yes")
{
cout << " Alright! Let us start converting your weight! " << endl;
}
else if (response == "no")
{
cout << " Too bad! We are going to do it anyway! " << endl;
}
else
{
cout << " That was not a proper response! Way to follow directions!, as consequence, we will do it!" << endl;
}
return userWeight;
}
double convert(double userWeight)
{
cout << " Well since 1 kilogram is equal to 2.2046226218 pounds, we need to divide your weight by that repeating number." << endl;
cout << " Since that number is very long and ugly, we will use 2.2046 for the sake of clarity." << endl;
double kiloWeight = (userWeight / 2.2046);
cout << "Your weight in pounds is " << userWeight << "lbs, divided by 2.2046 gives us" << kiloWeight << "kgs! " << endl;
}
int main()
{
string name1 = name();
height(name1);
weight(userWeight);
convert();
return 0;
}
You are doing it wrong. You should read about function signature and passing arguments.
You have defined weight as a function that doesn't take any arguments
double weight() { //...}
but you are calling it with some parameter userWeight in main function
weight(userWeight);
and this parameter in addition is not defined. ( And no: you cannot call a function with argument being local argument on the stack of function being called from same scope - it is technically possible but this is not what you want).
This should be something like:
int main() {
double userWeight = weight();
double result = convert( userWeight);
// we can see here that local variable named userWeight was assigned value
// from a call to weight() and this result is now being passed to convert
// now you can use a result from calling convert
//...
return 0;
}