I'm fairly new to programming with C++ and I'm trying to understand where I'm missing the flow of the algorithm in this code. The code is supposed to take the cost of a set of tickets ($25, $30, $15). When I run the code it will add the total number of tickets bought, but not the total cost of all the tickets. I'm believe I've assigned the variables correctly but I don't know why it isn't adding together the total cost unless I need to assign those variables separately.
Any help would be appreciated, thanks!
using namespace std;
int main()
{
//declare variables
double orchestra = 25;
double mainFloor = 30;
double balcony = 15;
double totalSales = 0.0;
//enter input items
cout << "Enter orchestra tickets ";
cin >> orchestra;
cout << "Enter main floor tickets ";
cin >> mainFloor;
cout << "Enter balcony tickets ";
cin >> balcony;
//add the input items and print the total
totalSales = orchestra + mainFloor + balcony;
//display the total sales
cout << "Total Sales $" << totalSales << endl;
system("pause");
return 0;
} //end of main function
As pointed it out in another comment, there was no explanation.
You are assigning the cost to the same variable that you are using for input on the number of tickets (and consequently overwriting the cost). Instead, put the costs in separate variables (or constants if you prefer) and then do the math after getting the user input.
Try this:
using namespace std;
int main()
{
//declare variables
double cost_per_orchestra = 25;
double cost_per_mainFloor = 30;
double cost_per_balcony = 15;
double orchestra = 0;
double mainFloor = 0;
double balcony = 0;
double totalSales = 0.0;
//enter input items
cout << "Enter orchestra tickets ";
cin >> orchestra;
cout << "Enter main floor tickets ";
cin >> mainFloor;
cout << "Enter balcony tickets ";
cin >> balcony;
//add the input items and print the total
totalSales = cost_per_orchestra * orchestra + cost_per_mainFloor * mainFloor + cost_per_balcony * balcony;
//display the total sales
cout << "Total Sales $" << totalSales << endl;
system("pause");
return 0;
} //end of main function
You're overwriting your price values with your cin statements: Better create separate variables for the price and multiply them with your input.
#include <iostream>
using namespace std;
int main(){
//declare variables
const double orchestraPrice = 25;
const double mainFloorPrice = 30;
const double balconyPrice = 15;
double orchestra = 0;
double mainFloor = 0;
double balcony = 0;
double totalSales = 0.0;
//enter input items
cout << "Enter orchestra tickets ";
cin >> orchestra;
cout << "Enter main floor tickets ";
cin >> mainFloor;
cout << "Enter balcony tickets ";
cin >> balcony;
//add the input items and print the total
totalSales = orchestra * orchestraPrice + mainFloor * mainFloorPrice + balcony * balconyPrice;
//display the total sales
cout << "Total Sales $" << totalSales << endl;
system("pause");
return 0;
} //end of main function
Instead of static declarations per ticket value you can take it at runtime. Yes, as previous answerer mentioned new input value is overwriting to variable.
#include <iostream>
#define MAX 3
using namespace std;
typedef struct
{
double ticket_type_per_cost;
double total_no_of_tickets;
}ticket;
int main()
{
double totalSales=0;
ticket t;
int i;
for(i=0; i<MAX; i++)
{
cout<< "\nenter cost per ticket of type "<<i+1 <<": ";
cin>>t.ticket_type_per_cost;
cout<<"\nenter number of tickets: ";
cin>>t.total_no_of_tickets;
totalSales= totalSales + (t.ticket_type_per_cost * t.total_no_of_tickets);
}
//display the total sales
cout << "Total Sales $" << totalSales << endl;
system("pause");
return 0;
} //end of main function
Related
I need help adding up several user inputed values using C++
double total; // Accumulates total
double price; // Gets next price from user
int numItems; // Number of items
int counter = 1; // Loop control counter
cout << "How many items do you have? ";
cin >> numItems;
cout << endl;
while (counter <= numItems) {
total = 0;
cout << "Enter the price of item " << counter << ": ";
cin >> price;
cout << endl;
total += price;
counter++;
}
cout << "The total price is: " << total << endl;
When I run my code, I end up getting the sum of only one value from the user
Yes, just as Chetan Ranpariya said:
total = 0; should be before while loop.
my program is a simple payroll calculator.
if the employee type is 0 any hours worked over 40 are time and a half.
if type is 1 they don't get overtime just straight pay.
I am trying to hold all the data in struct arrays. This is a homework assignment, and my program meets the requirements, but the issue im having is after i input hours for employees and then choose menu option c, my output is just zero.
Im not sure why exactly there wasn't any data outputted except zero in the column. I have no errors in my compiler.
What did I do wrong?
C++
#include <iostream>
#include <iomanip>
#include <string>
using namespace std;
//*********************************************************************************************
// Structure to hold employee ID, Name, Pay rate per hour, Employee type
//*********************************************************************************************
struct employeeRecord {
int IDnum; // holds employee id number
string name; // holds employess name
float payRate; // holds employee pay rate
int empType; // holds employee type
};
//*********************************************************************************************
// structure to hold time sheet
//*********************************************************************************************
struct timeSheet{
float hours; //hours worked
float grossPay; // gross pay
float netPay; // net pay
float taxAmount; // tax amount deduction
};
//*********************************************************************************************
// function prototype
//*********************************************************************************************
void addEmployee(employeeRecord *employee, int &index);
void addTime(timeSheet *time, employeeRecord *employee, int &index);
void calcTime(timeSheet *time, employeeRecord *employee, int &index, float taxRate);
void outTime(timeSheet *time, employeeRecord *employee, int &index);
//*********************************************************************************************
// main function
//*********************************************************************************************
int main(){
float taxRate = .15; // taxrate on pay
char choice; // holds user choice option
int index = 0; // index of array
// create struct arrays to hold data
employeeRecord employee[2];
timeSheet time[2];
// menu title
cout << "\nArmadillo Automotive Group Payroll\n" << endl;
//*********************************************************************************************
// do loop to cycle through menu options & validate input
//*********************************************************************************************
do{
//menu
cout << "\nMenu Options: \n";
cout << "A - Add Employee" << endl;
cout << "B - Add Employee's Hours" << endl;
cout << "C - Print Payroll Report" << endl;
//take user menu choice
cout << "\nEnter Menu Option: ";
cin >> choice;
choice = tolower(choice);
//validate user selection
while (choice != 'a' && choice != 'b' && choice!= 'c'){
cout << "Please enter 'A' 'B' or 'C' : ";
cin >> choice;
}
// Process menu selection choice
if (choice != 'c'){
if (choice == 'a'){
//process new employee
if (index < 2){
addEmployee(employee, index);
}
else{
cout << "\nEmployee index full" << endl;
}
}
// if choice 'b' add employee work hours
else{
addTime(time, employee, index);
}
}
}while (choice != 'c');
// calculates and stores employees time sheet information in struct array
calcTime(time, employee, index, taxRate);
//display pay check outputs
outTime(time, employee, index);
return 0;
}
//*********************************************************************************************
// function to add employee to index
//*********************************************************************************************
void addEmployee(employeeRecord *employee, int &index){
//take employees ID #
cout << "\nEnter employee's ID number: ";
cin >> employee[index].IDnum;
//validate employee id # is greater than 0
while (employee[index].IDnum < 0){
cout << "\nPlease enter an ID # above 0 : ";
cin >> employee[index].IDnum;
}
//take employees name
cout << "\nEnter employee's Name: ";
cin.ignore();
getline(cin, employee[index].name);
//validate line has characters only
//**********************
//**********************
//**********************
//take employees payrate
cout << "\nEnter employee's pay rate: $";
cin >> employee[index].payRate;
//validate payrate is amount above 0
while(employee[index].payRate < 0){
cout << "\nPlease enter a value greater than 0: ";
cin >> employee[index].payRate;
}
// take employees emptype
cout << "\nEnter Employee type \n";
cout << "0 for union, 1 for management: ";
cin >> employee[index].empType;
//validate 0 or 1 was entered
while(employee[index].empType != 0 && employee[index].empType != 1){
cout << "Enter 1 or 0: ";
cin >> employee[index].empType;
}
// increment index for future entry
index++;
}
//*********************************************************************************************
// function to add time to an employee
//*********************************************************************************************
void addTime(timeSheet *time, employeeRecord *employee, int &index){
//set index to zero to start with first employee on list
index = 0;
//main instruction
cout << "Enter timecard information for each employee: " << endl;
//enter hours for each employee for loop
for(int i=0; i < 2; i++){
cout << "Hours worked for " << employee[index].name << ": ";
cin >> time[index].hours;
index++;}
}
//*********************************************************************************************
// function to to calculate timesheet
//*********************************************************************************************
void calcTime(timeSheet *time, employeeRecord *employee, int &index, float taxRate){
index = 0; // set index back to zero to start at first array index
float tempHours; //temp hour hold
float overTime; // overTime hours
float hours = time[index].hours; //hours worked
float grossPay = time[index].grossPay; //employes's gross pay
float netPay = time[index].netPay; //employes's net pay
float taxAmount = time[index].taxAmount; ////employes's tax deduction
int empType = employee[index].empType; // employee type
float payRate = employee[index].payRate; // employes pay rate
for (int i=0; i < 2; i++){
if (empType == 0){
if(hours > 40){
tempHours = 40;
overTime = hours - 40;
grossPay = (overTime * (payRate * 1.5)) + (tempHours * payRate);
taxAmount = grossPay * taxRate;
netPay = grossPay - taxAmount;
}
else{
grossPay = hours * payRate;
taxAmount = grossPay * taxRate;
netPay = grossPay - taxAmount;
}
}
else{
grossPay = hours * payRate;
taxAmount = grossPay * taxRate;
netPay = grossPay - taxAmount;
}
// increase index number
index++;
}
}
//*********************************************************************************************
// function to to print out timesheet
//*********************************************************************************************
void outTime(timeSheet *time, employeeRecord *employee, int &index){
index = 0; // set index back to zero to start at first array index
int empID = employee[index].IDnum; //employes id number
string name = employee[index].name; // employees name
float grossPay = time[index].grossPay; //employes's gross pay
float taxAmount = time[index].taxAmount; ////employes's tax deduction
float netPay = time[index].netPay; //employes's net pay
cout << "Pay Roll Report\n" << endl;
cout << setw(10) << left << "ID" << setw(30) << left << "Name";
cout << setw(10) << right << "Gross Pay" << setw(10) << right << "Tax";
cout << setw(10) << right << "Net Pay" << endl;
// for loop to display employee information.'
for (int i=0; i < 2; i++){
cout << setw(10) << left << empID << setw(30) << left << name;
cout << setw(10) << right << grossPay << setw(10) << right << taxAmount;
cout << setw(10) << right << netPay << endl;
index++;}
}
I am getting an uninitialized Local variable error when I do believe I have already initialized. The error reads uninitialized local variable wk1 being used (It's wk1-wk5).
Here is the code:
#include <iostream>
using namespace std;
const double tax = 0.14;
int main()
{
int wk1,wk2,wk3,wk4,wk5;
wk1,wk2,wk3,wk4,wk5 = 0;
int thours = wk1 + wk2 + wk3 + wk4 + wk5; <------------ This is the error line.
thours = 0;
double payrate;
payrate = 0;
double gross = thours * payrate;
double taxes = tax * gross;
double net = gross - taxes;
double clothes = 0.10 * net;
double supplies = 0.10 * net;
double remaining = net - clothes - supplies;
double bonds = 0.25 * remaining;
double pbonds = 0.50 * bonds;
bonds = 0;
gross = 0;
net = 0;
clothes = 0;
supplies = 0;
remaining = 0;
cout << "Please enter the payrate for employee." << endl;
cin >> payrate;
payrate = 0;
cout << "Please enter employee's total hours for week one:" << endl;
cin >> wk1;
wk1 = 0;
cout << "Please enter employee's total hours for week two:" << endl;
cin >> wk2;
wk2 = 0;
cout << "Please enter employee's total hours for week three:" << endl;
cin >> wk3;
wk3 = 0;
cout << "Please enter employee's total hours for week four:" << endl;
cin >> wk4;
wk4 = 0;
cout << "Please enter employee's total hours for week five:" << endl;
cin >> wk5;
wk5 = 0;
cout << "Here is income before taxes: " << gross << endl;
cout << "Here is income after taxes: " << net << endl;
cout << "Here is clothes and accesories: " << clothes << endl;
cout << "Here is School supplies: " << supplies << endl;
cout << "Here is personal bonds: " << bonds << endl;
cout << "Here is parents bonds: " << pbonds << endl;
return 0;
}
wk1,wk2,wk3,wk4,wk5 = 0;
This line is a comma operator expression, which is equivalent to:
wk5 = 0;
Because expressions like wk1 has no side effect. Only the variable wk5 has been assigned a value, the other variables are still uninitialized. You can do:
wk1 = wk2 = wk3 = wk4 = wk5 = 0;
I have to make a loop to gather all the information from the users input of the employees. As you can see, I have gotten the parts where I ask the user how many employees and what their information is. Now all I have to is print that information to the screen like this, just without the periods between each and with a few spaces between each :
Weekly Payroll:
Name...............Title........Gross.......Tax.........Net
----------------------------------------
Ebenezer Scrooge.....................Partner...250.00......62.25.....187.75
Bob Cratchit...............................Clerk.......15.00........2.00.......13.00
And this is what I have :
#include <iostream>
using namespace std;
const int MAXSIZE = 20;
struct EmployeeT
{
char name[MAXSIZE];
char title;
double SSNum;
double Salary;
double Withholding_Exemptions;
};
EmployeeT employees[MAXSIZE];
int main()
{
cout << "How many Employees? ";
int numberOfEmployees;
cin >> numberOfEmployees;
while(numberOfEmployees > MAXSIZE)
{
cout << "Error: Maximum number of employees is 20\n" ;
cout << "How many Employees? ";
cin >> numberOfEmployees;
}
char name[MAXSIZE];
int title;
double SSNum;
double Salary;
double Withholding_Exemptions;
for (int count=0; count < numberOfEmployees; count++)
{
cout << "Name: ";
cin >> employees[ count ].name;
cout << "Title: ";
cin >> employees[ count ].title;
cout << "SSNum: \n";
cin >> employees[ count ].SSNum;
cout << "Salary: \n";
cin >> employees[ count ].Salary;
cout << "Withholding Exemptions: \n";
cin >> employees[ count ].Withholding_Exemptions;
}
double gross;
double tax;
double net;
double adjusted_income;
gross = employees[ count ].Salary;
adjusted_income = employees[ count ].Salary - 1.00;
tax = adjusted_income * .25;
net = gross - tax;
cout << "Weekly Payroll:\t Name \t Title \t Gross \t Tax \t Net \n";
for (int count=0; count < numberOfEmployees; count++)
{
cout << employees[count].name << " \t" << employees[count].title << " \t" <<
gross << "\t" << tax << "\t" << net << "\n";
}
system("pause");
}
Ok I updated the program. Now I'm trying to do the calculations. This what I'm doing...
To calculate payroll:
Gross pay is the weekly salary which was previously entered for the employee.
Net pay is calculated as the gross pay minus the amount of tax.
To calculate tax: Deduct $1 from the salary for each withholding exemption. This is the adjusted income. If the adjusted income is less than 0, then use 0 as the adjusted income.
Multiply the adjusted income by the tax rate, which you should assume is a flat 25%.
As an example, if Bob Cratchit has a weekly income of $15 and 7 dependents, then his adjusted income would be $8. His tax would be 25% of $8 which is $2, and therefore his net pay is $13.
I have started trying to get this. I put it between the second loop and the last loop. Is this right?
A small example for printing columns using C++ streams:
#include <iomanip>
#include <ios>
std::ostream& operator<<(std::ostream& a_out, const EmployeeT& a_e)
{
a_out << std::setfill(' ')
<< std::left
<< std::setw(sizeof(a_e.name))
<< a_e.name
<< std::setw(0)
<< a_e.title
<< " "
<< std::setw(10)
<< a_e.SSNum
<< a_e.Salary
<< a_e.Withholding_Exemptions;
return a_out;
}
This would allow you to write an employee to standard output using:
std::cout << employees[n] << "\n";
Use a similar approach for the column headings.
Other points:
Prefer std::string to char[] (or char*) then you don't have to limit the length of the string (or explicitly manage the memory)
Use std::vector instead of a fixed array to avoid a limit
Make use of STL algorithms (std::for_each, std::copy for example) for performing operations on elements in containers (or array)
you can use the same loop for insertion and displaying or anything!! because it traverses through the whole loop.
cout << "Weekly Payroll:\t Name \t Title \t Gross \t Tax \t Net \n";
for (int count=0; count < numberOfEmployees; count++)
{
cout << employees[count].name << " \t" << employees[count].title << " \t" <<
Gross << "\t" << tax << "\t" << Net << "\n";
}
Find net,tax and gross of each structure object and print.
Check if you want name as int at the marked position.
#include <iostream>
using namespace std;
const int MAXSIZE = 20;
struct EmployeeT {
char name[MAXSIZE];
char title;
double SSNum;
double Salary;
double Withholding_Exemptions;
};
EmployeeT employees[MAXSIZE];
int main() {
cout << "How many Employees? ";
int numberOfEmployees;
cin >> numberOfEmployees;
while(numberOfEmployees > MAXSIZE) {
cout << "Error: Maximum number of employees is 20\n" <<
"How many Employees? ";
cin >> numberOfEmployees;
}
int name; // name is char[] or string
int title;
double SSNum;
double Salary;
double Withholding_Exemptions;
for (int count = 0; count < numberOfEmployees; count++) {
cout << "Name: \n";
cin >> employees[ count ].name;
cout << "Title: \n";
cin >> employees[ count ].title;
cout << "SSNum: \n";
cin >> employees[ count ].SSNum;
cout << "Salary: \n";
cin >> employees[ count ].Salary;
cout << "Withholding Exemptions: ";
cin >> employees[ count ].Withholding_Exemptions;
}
}
You can use the '\t' sequence, which represent in C++ a "Tab space" (like when you press Tab on your Keyboard).
As for the loop, it should be something like:
cout << "Weekly Payroll:\t Name \t Title \t Gross \t Tax \t Net \n";
for(int n=0; n < employees; n++)
{
cout << employees[n].name << " \t" << employees[n].title << " \t" ...... << "\n";
}
It should work :)
You could look into the STL iomanip header functions, like setw()
Formatting Cout Output in C++ using iomanip
. With that it should be possible to get decent fix sized columns, which tabs likely wont.
Your code has seems OK, although it is more complicated than it should be, and the input-loop has no error-handling (if a user enters something invalid, your program will stop working).
Here are some general pointers that can help you make your program better:
Use std::vector<EmployeeT> instead of an array - this way you don't have to limit the number of employees you can handle, because the vector can grow dynamically.
Provide an operator<<-overload for EmployeeT.
Look into Iostream-manipulators, particularly std::setw; This question is similar to your problem, and one solution uses manipulators to format the output.
Effective January 1st of each year, Gabby recieves a 5% raise on her previous year's salary. She wants a program that calculates and displays the amount of her annual raises for the next three years. The program also should calculate and display her total salary for the three years.
I have to test the program and this is what i get but when i desk check it comes out wrong.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
const double RATE = .05;
double salary = 0.0;
double raise = 0.0;
double totalSalary = 0.0;
cout << "Enter the salary:";
cin >> salary;
for(int counter = 0; counter <=3; counter++)
{
cout <<salary<<endl;
raise = (salary * 0.05);
}
return 0;
} //end of main function
You're not adding the raise to the salary:
salary += raise;
This one is a little more accurate. It will calculate with decimals without rounding and post the raise for each year, then add how much the total of her raises will be over three years. Also, some notes are added so you know what was going on in the code.
#include <iostream>
#include <iomanip>
using namespace std;
int main()
{
//declare variables
double salary = 0.0;
double totalSalary = 0.0;
const double RATE = 0.05;
//input
cout << "Enter the salary: ";
cin >> salary;
cout << endl;
//loop for years and calculation
for(int numYears = 1; numYears <= 3; numYears ++)
{
cout << fixed;
cout << setprecision(2);
salary = salary*(1+RATE);
cout << "Year " << numYears;
cout << ": $" << salary << endl;
//end for
}
cout << "The total salary over three years is $" << totalSalary << endl;
cout << endl;
system("pause");
return 0;
}
First of all, you declare a constant called RATE (which should really be at the top of the program rather than in your main function) but don't bother to use this in your calculation. Instead you use the hard-coded value of 0.05.
Second, you're not adding the calculation to the salary variable. You can use salary += raise or salary *= (1.0 + RATE).
Third, you're not doing anything with the totalSalary variable at all.
Your code should look something like this:
#include <iostream>
using namespace std;
const double RATE = 0.05;
int main()
{
double salary = 0.0;
double totalSalary = 0.0;
cout << "Enter the salary:" << endl;
cin >> salary;
for(int counter = 0; counter <=3; counter++)
{
cout << salary << endl;
salary *= (1.0 + RATE);\
totalSalary += salary;
}
cout << "The total salary is " << totalSalary << endl;
return 0;
}