I am trying to write this assignment for school where the program has to calculate the regular pay, overtime pay and total pay separately. I would like to also include a statement where it mentions that if the number entered by the user is negative, the program would tell the user that the number entered is invalid so I have added it but it but it shows an error on the "else if" line. Im also trying to add a function where it calculates the total pay for the user but I don't know how to do it.
this is my code
#include <iostream>;
#include <iomanip>;
using namespace std;
int main ()
{
double hoursworked, hourlyrate, regularpay, overtimepay, totalpay;
int MIN_HOURSWORKED = 1,
MIN_HOURLYRATE = 1;
cout << "type in how many hours have you worked this week.\n";
cin >> hoursworked;
cout << "type in your hourlyrate.\n";
cin >> hourlyrate;
if (hoursworked < MIN_HOURSWORKED && MIN_HOURLYRATE < 0)
{
if (40 > hoursworked)
regularpay = hoursworked * hourlyrate;
cout << "your regular pay is : $ " << regularpay << endl;
else if (hoursworked > 40)
overtimepay = (hoursworked - 40) * 1.5 * hourlyrate;
cout << " your overtime pay is: $" << overtimepay << endl;
}
else
{
cout << "you entered an invalid number.";
cout << "please enter a number that is bigger than 0" << endl;
}
return 0 ;
}
Here are the code changes I made and the comments explain why
#include <iostream>
using namespace std;
int main()
{
//By initializing hoursworked and hourlyrate as negative, it ensures that the while loops used in the cin is used at least once
double hoursworked=-1, hourlyrate=-1, regularpay, overtimepay, totalpay;
int MIN_HOURSWORKED = 1,
MIN_HOURLYRATE = 1;
cout << "type in how many hours have you worked this week.\n";
//Until hoursworked is positive the loop will keep running
while(hoursworked<0)
{cout<<"Enter a positive value"<<endl; cin >> hoursworked;}
//Until hourlyrate is positive the loop will keep running
cout << "type in your hourlyrate.\n";
while(hourlyrate<0)
{cout<<"Enter a positive value"<<endl; cin >> hourlyrate;}
//Your previous code (hoursworked<MIN_HOURSWORKED
//&& MIN_HOURLYRATE<0) ensures that hoursworked is lesser than
//min_hoursworked and that min_hourlyrate is less than 0. Which
//Im sure is not what you want to do
if (hoursworked>MIN_HOURSWORKED && hourlyrate>MIN_HOURLYRATE)
{
if (40>hoursworked)
{
regularpay = hoursworked * hourlyrate;
cout << "your regular pay is : $ " << regularpay << endl;
}
else if (hoursworked>40)
{
overtimepay = (hoursworked - 40) * 1.5 * hourlyrate;
cout << " your overtime pay is: $" << overtimepay << endl;
}
}
else
{
cout << "you entered an invalid number.";
cout << "please enter a number that is bigger than 0" << endl;
}
return 0;
}
The way you make a function is explained well HERE
Also the reason why you were getting errors in your if and else if because of brackets {}. As a new coder, use {} everywhere even when it seems like you don't need to. It is good practice and helps keep a lot of confusions at bay
P.S. Please accept my answer if you find it useful as that would help me get some reputation points
An if clause with two or more statements requires braces to be used:
if ( /* condition */ )
{
statement;
statement;
...
}
The omission of the braces means that only the first statement after the if statement "belongs" to it:
if (40 > hoursworked)
regularpay = hoursworked * hourlyrate;
That's the entire if statement, and nothing else. A few lines below, an else if appears out of nowhere. Your compiler gets confused, and complains about it.
Your outermost if statement already includes these braces, so you simply forgot to use them here.
Although this will solve the compilation error, the resulting code will still not work right, for at least three reasons.
An hoursworked of exactly 40 will not meet either of the if conditions, and nothing will be printed.
An hoursworked in excess of 40 will not meet the first if's condition, so the first message does not get printed. This seems to be a rather obvious mistake.
The outermost if condition gets met only if both of these are true:
if (hoursworked < MIN_HOURSWORKED && MIN_HOURLYRATE < 0)
If you read this verbatim, this means: do all if the following are all true: hoursworked is less than the minimum allowed, and the hourly rate is negative. So, if someone would enter -5 hours worked, and an hourly rate of -10, this condition will be met. This will be considered valid input, and the statements inside this if statement will execute, otherwise the input is rejected as invalid.
That, also, is obviously incorrect.
So, in addition to fixing the compilation error, you will also need to make additional changes to your program, in order to correct all of these defects. Good luck.
Related
I'm very new to c++ and still in the process of learning it.
I've been assigned to create a simple bank simulator and just stumble upon a problem i can't seem to figure out for some reason.
Whenever i try to check the balance it shows me some numbers and letters and my first thought was either it showed the memory adress or a overflow.
I could deposit something first and it will be added to the balance variable and shows up in the program aswell without some awkward numbers and letters. My goal is to make sure that the balance is always showing a 0 until the user deposit or withdraw from it.
I somehow managed to fix this by using float instead of double, I'm not really sure why it worked at this point since I'm way to tired to even think about it, but I would rather use double since this program might use more data.
If anything seems unclear of what I'm trying to say I'll try and answer your question as soon as I can. I also add a image here to show you what I'm talking about.
#include <iostream>
using namespace std;
int main()
{
while(true){
cout << "[D]eposit\n";
cout << "[W]ithdrawal\n";
cout << "[B]alance\n";
cout << "[I]nterest payment\n";
cout << "[E]xit\n";
char menu;
double balance, deposit, withdraw;
cin >> menu;
switch(menu)
{
case'D':
cout << "[DEPOSIT]\n" << "Deposit: ";
cin >> deposit;
balance += deposit;
continue;
case'W':
cout <<"[WITHDRAWAL]\n" << "Withdraw: ";
cin >> withdraw;
balance -= withdraw;
continue;
case'B':
cout << "[BALANCE]\n" << "Amount: " << balance;
continue;
case'I':
cout << "[INTEREST PAYMENT]\n";
continue;
case 'E':
cout << "Program is closing...";
break;
default:
cout << "Please use uppercase letters";
continue;
}
break;
}
return 0;
}
Balance isn't initialized, so when you add / substract an amount, the result is odd due to the random initial value of balance.
Well the main reason for getting the gibberish data is because your balance variable is uninitialized, and accessing it is undefined behaviour.
You can fix it by doing this:
double balance = 0;
double deposit, withdraw;
Also, your program won't work as expected because you declare the balance variable inside the while loop. Just declaring the variables outside the loop will make it work as expected.
double balance = 0;
double deposit, withdraw;
while(true){
...
}
I am a C++ noob.
I am trying to work on this text-based game for school, and I am having trouble with displaying the correct percentage. I think this has to do with how I calculate it in the program, or I am screwing something up with the function.
I would be most grateful for some assistance. Cheers.
#include <string>
#include <cmath>
#include <iostream>
using namespace std;
double menu (float crew_count);
double calculatePct(float crew_count, float number_of_deaths)
{
double percent = ((crew_count - number_of_deaths) / crew_count) * 100;
}
double welcome ()
{
int crew_count;
string backstory = "\nYou are in charge of a top-secret military mission, when your\nspace ship makes an emergency landing, on the largest moon of planet Gork.\nThe space ship is damaged. Oxygen levels begin to drop.\nHow many military personnel are on your ship?\nNumber of personnel: ";
cout << backstory;
cin >> crew_count;
if (crew_count >= 1)
menu(crew_count);
else if (crew_count < 1)
cout << "\nThere must be 1 or more members of the crew! Please enter a valid number!\n";
}
double menu (float crew_count)
{
double percent;
double main_option;
cout << "\nChoose one:\n1. Attempt repairs on the ship.\n2. Request an emergency rescue from mission command.\n3. Break protocol and reveal the top-secret space ship's location,\nto the Russians on a nearby moon, asking for their assistance.\nYour choice: ";
cin >> main_option;
if (main_option == 1)
{
cout << "\nToxic material on the moon has corroded the launch gear, and the \nlaunch exploded!\n\nThere were no survivors.\n";
}
else if (main_option == 2)
{
cout << "\nThe oxygen was depleted before the rescue team arrived.\nThere were 4 people killed.\n";
if (crew_count <=4)
cout << "0% of crew members were rescued!\n";
else
float percent = calculatePct(crew_count, 4);
cout << percent << "% of the crew was rescued.\n";
}
else if (main_option == 3)
{
cout << "\nThe Russians agree to send a rescue ship, but secretly attempt to hack into the ships systems remotely, which triggers an automatic shut down of all\ncommunications systems and locks all mission critical storage units, including\none of the storage unit that holds emergency oxygen tanks.\n\nOne quarter of all personnel are lost.\n";
}
else if (main_option != 1, 2, 3)
{
cout << "\nYou have been eaten by a Grue!\n";
}
}
int main()
{
cout << "Welcome to Gork 1.0\nCreated by Cortez Phenix\nTo make selections, enter the number of each option!\n\n";
int choice;
cout << "What would you like to do?\n1. Play Game\n2. Exit\nYour Choice: ";
cin >> choice;
if (choice == 1)
welcome();
else if (choice == 2)
cout << "\nGoodbye!\n";
else
cout << "\nPlease choose 1 or 2.\n";
return 0;
}
Excuse me. I'm sure this post is hectic.
IMAGE: At the bottom, you can see the queer number
If we do some slight reformatting on parts of your code, it looks like this:
if (crew_count <=4)
cout << "0% of crew members were rescued!\n";
else
float percent = calculatePct(crew_count, 4);
cout << percent << "% of the crew was rescued.\n";
The value you print is not the value calculated by calculatePct, it's the indeterminate value of the percent variable defined earlier in the function.
In short: You forgot your curly-braces:
if (crew_count <=4)
cout << "0% of crew members were rescued!\n";
else
{ // Note curly brace here
float percent = calculatePct(crew_count, 4);
cout << percent << "% of the crew was rescued.\n";
} // And also here
I recommend you enable more verbose warnings, as the compiler should be able to detect that you use the uninitialized variable, as well as the new variable being initialized but not used.
you mixed intergers and floats and void
int crew_count then you fed double menu(float crew_count).
your menu function doesnt return anything its supossed to be void so does your welcome function
Also you calculatePct does not return the calculated percentage. Do that by adding return percent;
See if it helps
c++ and I'm trying to figure out why my code returns 0's from a few statements after the user inputs some float numbers. I'm not sure why. Maybe someone can help:
This is what I get after running my method and answering the questions before it:
The number of gallons of paint required is: 0 gallons
Hours of labor that is required: 0 hours
.
Also ignore the () around my # in the beginning. I will put periods between lines to make it look neater on this website.
/**
* A painting company has determined that for every 160 square feet of wall
space, one gallon of paint and 3 hours of labor are required.
* The company charges the $28.00 per hour for labor.
* Design a modular program that allows the user to enter the number of rooms
that are to be painted,
* the approximate square feet of wall space in each room (may differ from room
to room), and the price per gallon of paint.
* It should then create a report that includes a fancy company header and
displays the following information:
* The number of gallons of paint required: (Rounded up to the next full
gallon)
* The hours of labor required:
* The cost of the paint:
* The labor charges:
* Total cost of the paint job:
* Requirements:
* Input validation: The program should not accept a value less than 1 or
more than 12 for the number of rooms
* Should not accept a value less than 100 for the square
footage of a room.
* Should not accept a value less than $10.00 or more
than $25.00 for the price of a gallon of paint
*
* Lets do this...
*/
#include <iostream>
#include <cmath>
#include <iomanip>
using namespace std;
float priceOfGallon(float);
float numberOfGallons(float, float);
float totalWallArea(float, float, float);
float laborHours(float, float);
void fancyCompanyHeader();
int main() {
float area;
float totalArea;
float min_labor = 3;
float number_of_rooms;
float number_of_gallons;
float price_of_gallon;
totalWallArea(area, totalArea, number_of_rooms);
priceOfGallon(price_of_gallon);
numberOfGallons(number_of_gallons, totalArea);
laborHours(number_of_gallons, min_labor);
fancyCompanyHeader();
return 0;
}
// function that gets the number of gallons needed for the total area
float numberOfGallons(float number_of_gallons, float totalArea) {
number_of_gallons = (totalArea / 160.0);
std::cout << "The number of gallons of paint required is: " <<
number_of_gallons << " gallons" << std::endl;
}
float priceOfGallon(float price_of_gallon){
std::cout << "Please enter the price per gallon: " << std::endl;
cin >> price_of_gallon;
while(price_of_gallon < 10.00 || price_of_gallon > 25.00) {
std::cout << "The price should be between $10.00 and $25.00. Please try again: " << std::endl;
cin >> price_of_gallon;
}
}
float totalWallArea(float area, float totalArea, float number_of_rooms) {
std::cout << "Please enter the number of rooms that needs to be painted:" <<
std::endl;
std::cin >> number_of_rooms;
while(number_of_rooms < 1)
{
cout << "Number of rooms must be at least one. Please try again: " <<
std::endl;
cin >> number_of_rooms;
}
for(float i = 1; i <= number_of_rooms; i++)
{
cout << "Please enter the square feet of wall space needed for Room " <<
i << std::endl;
cin >> area;
while(area < 100)
{
std::cout << "The area should be 100 or greater. Please try again: "
<< std::endl;
cin >> area;
}
totalArea += area;
}
}
// I will finish this method later
float laborHours(float number_of_gallons, float min_labor) {
min_labor = number_of_gallons * 28.00;
std::cout << "Hours of labor that is required: " << min_labor << " hours "
<< std::endl;
return min_labor;
}
You need to make all of those variables you are modifying global (Declared outside of int main()). In C++, when you give a function a variable, it will just copy the contents of the variable into the function's variables: the original variable passed in remains constant. Thus, your uninitialized floats default to 0 and are not changed by any of the functions, so when they are given to the laborHours function or numberOfHours function, 0s are passed into each.
Example with much better practices than in your code (it's ok, everyone starts by writing atrocious code) :
#include <iostream>
int walls,rooms,total_walls; //It only makes sense if all of these are integers.
//These are global declarations, they can be modified by any function in the program
void input_walls() {
/* Functions are notated as so in C++:
{return type} {function_name}({input},{input},...)
It's pointless to annotate functions that don't return anything
with a declaration of a float return type (they'll just return 0 */
std::cin >> walls;
while(walls < 0) {
std::cout << "Please input a positive amount of walls per room.";
std::cin >> walls;
}
}
void input_rooms() {
std::cin >> rooms;
while(rooms < 0) {
std::cout << "Please input a positive amount of rooms";
std::cin >> rooms;
}
}
void calculate_result() {
total_walls = walls*rooms;
}
void output_result() {
std::cout << "I'll need to paint " << total_walls << " walls!" << std::endl;
}
int main() {
input_walls();
input_rooms();
calculate_result();
output_result();
}
This still isn't the best way to write this, but it's still the exact same thing you were trying to do. Now try rewriting what you were trying to do in this style!
TLDR/Quick fix: Make the variable definitions global, cut out the arguments from the functions.
I am attempting to construct a mileage calculator. The design is like this,
If a person drives 100 miles or less then the amount they shall be paid 25 cent per mile.
If a person drives in excess of 100 miles, they shall be paid the initial 25 cents for their first 100 miles in addition to 15 cents for every mile over 100 mile...
So an example would be
10 miles would earn the person a dollar, while 250 miles would earn (25 for the first 100 + 22.50 for the second 150) to a grand total of 47.50..
When I hit start without debugging, the program goes to the black screen to put values in. But then I receive an error message.. I am trying to figure out what it means.
I am using microsoft visual studio 2008. C++ coding.
#include <iostream>
using namespace std;
int main()
{
int varOne ;
cout << "Enter your favorite number" << endl;
cin << varOne << endl;
if(varOne <= 100)
cout << (1/4)*(varOne)<< endl;
if (varOne>= 100)
cout << (.15 * (varOne-100)) + (.25 * 100) <, endl;
return 0;
}
Debug Error!
Program ... isual Studio
2008\Projects\practice\Debug\rorioodweorrfhur.exe
Module: ... isual studio
2008\Projects\practice\Debug\rorioodweorfhur.exe
File:
Run-Time Check Failure #3 - The variable 'var1' is being used without being initialized.
(Press Retry to debug the application)
Here are some simple errors I noticed in your code
cin << varOne << endl;
It should be
cin >> varOne ;
Next error
cout << (.15 * (varOne-100)) + (.25 * 100) <, endl;
This should be
cout << (.15 * (varOne-100)) + (.25 * 100) << endl;
Here are some logical errors.
In your If statements, you are checking >= and <= , Check for equality only once. Change
if(varOne <= 100)
to
if(varOne < 100)
Also change
cout<< (1/4)*(varOne) << endl;
to
cout<< (varOne)/4 << endl;
This is because 1/4 will give 0
This question already has answers here:
Closed 12 years ago.
Possible Duplicate:
C++ passing variables in from one Function to the Next.
The Program is working but when it comes to getUserData it asks for the same information 4 times and then displays the results with negative numbers. I used test numbers for number of rooms 1, 110 for sqrt feet in the room, 15.00 for cost of paint.
//Problems with this not working
void showMenu();
void getUserData(int &, double &, int &);
void doEstimate(int &, double &, int &, double &, double &);
void showReport();
int main()
{
int choice;
//I am not sure why I have to do this but someone suggested to do it and the program complied when I did this int calc ect
int calcGallonsOfPaint, rooms, totalsqrtfeet;
double calcCostOfPaint, costOfPaint;
int calcHoursOfLabor;
double calcLaborCost;
double calcPaintJobCost;
// Set up numeric output formatting.
cout << fixed << showpoint << setprecision(2);
do
{
// Display the menu and get the user's choice.
showMenu();
cin >> choice;
// Validate the menu selection.
while (choice < 1 || choice > 2)
{
cout << "Please enter 1 or 2: ";
cin >> choice;
}
if (choice == 1)
{
//for some reason it just keeps repeating the function getUserData
getUserData(rooms, costOfPaint, totalsqrtfeet);
doEstimate(calcGallonsOfPaint, calcCostOfPaint, calcHoursOfLabor, calcLaborCost, calcPaintJobCost);
showReport();
}
} while (choice != 2);
return 0;
}
void getUserData(int &rooms, double &costOfPaint, int &totalsqrtfeet)
{
int sqrtfeet;
int count = 0;
cout << "Please enter the number of rooms to be painted: ";
cin >> rooms;
cout << "Please enter square feet of wall space in each room: ";
cin >> sqrtfeet;
for (count = 1; count <= rooms; count++)
{
cout << "Please eneter square feet of wall space in room " << count << ": ";
cin >> sqrtfeet;
totalsqrtfeet += sqrtfeet;
}
cout << "What is the cost of the paint: ";
cin >> costOfPaint;
system("cls");
system("pause");
}
void doEstimate(int &calcGallonsOfPaint, double &calcCostOfPaint, int &calcHoursOfLabor, double &calcLaborCost, double &calcPaintJobCost)
{
//I am not sure why I have to do this but someone suggested to do it and the program complied when I did this: puting int rooms ect
int rooms, totalsqrtfeet;
double costOfPaint;
getUserData(rooms, costOfPaint, totalsqrtfeet);
calcGallonsOfPaint = 1 * (totalsqrtfeet/110); //Calculates the number of whole gallons of paint required.
calcCostOfPaint = calcGallonsOfPaint * costOfPaint; //Calculates the cost of the paint required.
calcHoursOfLabor = calcGallonsOfPaint * 6; //Calculates the number of whole hours of labor required.
calcLaborCost = calcHoursOfLabor * 15.00; //Calculates the labor charges.
//Calculates the cost of the paint job. This is the sum of the labor charges and the cost of the paint required.
calcPaintJobCost = calcLaborCost + calcCostOfPaint;
/*110 square feet of wall space
one gallon of paint
six hours of labor
$15.00 per hour for labor
*/
}
void showReport()
{
//I am not sure why I have to do this but someone suggested to do it and the program complied when I did this
int calcGallonsOfPaint, rooms, totalsqrtfeet;
double calcCostOfPaint, costOfPaint;
int calcHoursOfLabor;
double calcLaborCost;
double calcPaintJobCost;
getUserData(rooms, costOfPaint, totalsqrtfeet);
doEstimate(calcGallonsOfPaint, calcCostOfPaint, calcHoursOfLabor, calcLaborCost, calcPaintJobCost);
cout << "The number of rooms to be painted: " << rooms << endl;
cout << "The number of whole gallons of paint required: " << calcGallonsOfPaint << endl;
cout << "The hours of labor required: " << calcHoursOfLabor << endl;
cout << "The cost of the paint: " << calcCostOfPaint << endl;
cout << "The labor charges: " << calcLaborCost << endl;
cout << "The total cost of the paint job: " << calcPaintJobCost << endl;
system("pause");
system("cls");
}
One thing that you should do is initialise totalsqrtfeet to zero in your main function. That's because you're just adding the size of each room to it and it starts out with a random value: junk + a + b + c + d is still junk :-)
On top of that, you call getUserData from your main function and then again from doEstimate. And then you call them both again in showReport. That's why it's asking four times. Just call getUserData once. Since it's homework, I'll leave you to figure out where but here's a hint. If you do it in main (nudge, nudge, wink, wink), you'll have to pass he variables into doEstimate as well, not create new variables of the same name within that function and magically expect the compiler to associate them with the originals.
To caveat on what paxdiablo said, you are calling getUserData in your nested while loop, but I don't understand the purpose of calling getUserData(rooms, costOfPaint, totalsqrtfeet); prior to doEstimate(...) when the data isn't used nor passed to doEstimate(...) until you call getUserData again while inside the doEstimate(...) function. You should pass by value the rooms, costOfPaint, and totalsqrtfeet variables to doEstimate(...) or make them global since you only have one main() function anyways. If you had some sort of OO solution, then I wouldn't recommend making them global and rather part of a class.
Also all these variables are ZERO or NULL when they are passed into doEstimate(...):
calcGallonsOfPaint, calcCostOfPaint, calcHoursOfLabor, calcLaborCost, calcPaintJobCost
If you want to output them, then you need to pass them by reference to doEstimate(...) and then when it gets to the cout then it will sufficiently print the correct values. That is why it is zero.
The bottom line is though you need one function to call the other functions. That would be the simplest plan at this point, such as:
GetDataAndPrint(...) {
// Get some data
// Do estimate, pass in values by reference
// Print Results from calculated values
// return
}