SOLVED 11/19/2017 # 10:20PM
This is the codeblock I'm working on, and I need to implement a while loop to run it infinitely until the user is satisfied. I'm not sure if gross_pay should be in the condition or if something else needs to be there. I keep on getting this error code. (error C4700: uninitialized local variable 'gross_pay' used)
// GrossPay.cpp : Defines the entry point for the console application.
//int temp = 0;
#include "stdafx.h"
#include <iostream>
#include <stdio.h>
#include <stdlib.h>
using namespace std;
int main()
{
double hourly_rate;
double hours;
double gross_pay;
while ( gross_pay >= 1 ) {
printf("Please input the hourly rate of the employee: ");
cin >> hourly_rate;
printf("Please input the number of hours worked by the employee: ");
cin >> hours;
if (hours <= 40)
{
gross_pay = hours * hourly_rate;
}
else
{
gross_pay = (40 * hourly_rate) + (hours - 40) * (hourly_rate * 1.5);
}
cout << "The gross pay of this employee is $" << gross_pay << "." << endl;
system("pause");
return 0;
}
}
Solution:
// GrossPay.cpp : Defines the entry point for the console application.
#include "stdafx.h"
#include <iostream>
using namespace std;
int main()
{
double hourly_rate;
double hours;
double gross_pay = 1;
while (gross_pay >= 1) {
printf("Please input the hourly rate of the employee: ");
cin >> hourly_rate;
printf("Please input the number of hours worked by the employee: ");
cin >> hours;
if (hours <= 40)
{
gross_pay = hours * hourly_rate;
}
else
{
gross_pay = (40 * hourly_rate) + (hours - 40) * (hourly_rate *
1.5);
}
cout << "The gross pay of this employee is $" << gross_pay << "." <<
endl;
}
return 0;
}
Every variable should be initialized before you are using for an operation otherwise the result may not be same as you expected.
Rewrite as double gross_pay = 1;
If you don't specify an initialization value then the value for double gross_pay is undefined. It will set to 0 for global variable.
The error message says everything, you have to initialize gross_pay first, otherwise its value is undefined
double gross_pay = 1;
Or you can change while loop to do-while
do {
printf("Please input the hourly rate of the employee: ");
cin >> hourly_rate;
.....
.........
} while ( gross_pay >= 1 );
Related
I'm currently doing a Zybooks lesson for my C++ class and we're going over while loops. In this question, it wants me to calculate how many years it takes for a bank account to double it's initial balance. There is also an annual contribution added. My code is as follows:
#include <iostream>
using namespace std;
int main()
{
const double RATE = 5;
const double INITIAL_BALANCE = 10000;
const double TARGET = 2 * INITIAL_BALANCE;
cout << "Annual contribution: " << endl;
double contribution;
cin >> contribution;
double balance = INITIAL_BALANCE;
int year = 0;
while (balance < TARGET)
{
year++;
double interest = balance * RATE / 100;
balance = balance + interest + contribution;
}
cout << "Year: " << year << endl;
cout << "Balance: " << balance << endl;
return 0;
}
I used this as an answer but was met with this unexpected result:
Output differs. See highlights below.
Input
100
Your output
Annual contribution:
Year: 13
Balance: 20627.8
Expected output
Annual contribution:
Year: 13
Balance: 20527.8
I see the expected output and your output differs by a 100, i.e. your contribution. Maybe the evaluation system doesn't add annual contribution once your target is reached. The below code gets your required output, but I think your code should have been the correct answer.
#include <iostream>
using namespace std;
int main()
{
const double RATE = 5;
const double INITIAL_BALANCE = 10000;
const double TARGET = 2 * INITIAL_BALANCE;
cout << "Annual contribution: " << endl;
double contribution;
cin >> contribution;
double balance = INITIAL_BALANCE;
int year = 0;
while (balance < TARGET)
{
year++;
double interest = balance * RATE / 100;
balance = balance + interest;
if (balance < TARGET) {
balance += contribution;
}
}
cout << "Year: " << year << endl;
cout << "Balance: " << balance << endl;
return 0;
}
The problem is that you're making a contribution after the 13th year even though the target has been reached.
I would restructure to something like this, in order to only check the condition once:
while (true)
{
year++;
double interest = balance * RATE / 100;
balance += interest;
if (balance >= TARGET)
{
break;
}
balance += contribution;
}
This is because the last time the loop is being executed (at year=13), balance is less than TARGET but, after adding a contribution and interest into it, it jumps out of the loop with contribution and interest added to it.
So, the solution can be to use an if statement within the while loop to check if it exceeds the TARGET; if it does, then don't add contribution into it.
Replace your while loop with the following:
while (balance < TARGET)
{
year++;
double interest = balance * RATE / 100;
balance = balance + interest;
if (balance < TARGET) {
balance += contribution;
}
}
I've been trying to figure this out for sometime and I think it has something to do with the values I'm using for the calculations. I'm not exactly familiar with compound interest so I'm not sure were I'm going wrong. Any help would be appreciated.
#include <iostream>
#include <cmath>
using namespace std;
double interest_credit_card(double initial_balance, double interest_rate, int payment_months);
// Calculates interest on a credit card account according to initial balance,
//interest rate, and number of payment months.
int main ()
{
double initial_balance, interest_rate;
int payment_months;
char answer;
do
{
cout << "Enter your initial balace: \n";
cin >> initial_balance;
cout << "For how many months will you be making payments?\n";
cin >> payment_months;
cout << "What is your interest rate (as a percent)?: %\n";
cin >> interest_rate;
cout << endl;
cout << "You will be paying: $ " << interest_credit_card( initial_balance, interest_rate, payment_months) << endl;
cout << "Would you like to try again? (Y/N)\n";
cin >> answer;
}while (answer == 'Y' || answer == 'y');
cout << "Good-Bye.\n";
return 0;
}
double interest_credit_card(double initial_balance, double interest_rate, int payment_months)
{
double compound_interest, compounding, compounding2, compounding3, compounding4;
while(payment_months > 0)
{
initial_balance = initial_balance + (initial_balance * interest_rate/100.0);
compounding = (interest_rate /12);
compounding2 = compounding + 1;
compounding3 = interest_rate * (payment_months/12);
compounding4 = pow(compounding2, compounding3);
compound_interest = initial_balance * compounding4;
initial_balance = initial_balance + compound_interest;
payment_months--;
}
return initial_balance;
}
Inputs and expected outputs:
Enter your initial balance: 1000
For how many months will you be making payments?: 7
What is your interest rate (as a percent)?: 9
You will be paying: $1053.70
It looks like you were trying a bunch of things and then left them in. The first solution you tried was almost right, you just forgot "/12":
double interest_credit_card(double initial_balance, double interest_rate, int payment_months)
{
while (payment_months > 0)
{
initial_balance = initial_balance + (initial_balance * interest_rate / 100.0/12);
payment_months--;
}
return initial_balance;
}
With a little better style:
double interest_credit_card(double initial_balance, double interest_rate, int payment_months)
{
double total_payment = initial_balance;
double monthly_rate = interest_rate / 100.0 / 12;
for (int month = 1; month <= payment_months; ++month)
total_payment += total_payment * monthly_rate;
return total_payment;
}
4.16 (Salary Calculator) Develop a C++ program that uses a while statement to determine the
gross pay for each of several employees.
When someone works 41 hours or more. They get paid 1.5x more so my problem is that in my else if statement. I did rate * 1.5 which should translate into 10 * 1.5 = 15 but I get 425 because my code on the top probably, but I don't understand it at the moment.
He gave us this example. Which I'm trying to emulate.
"
Enter hours worked (-1 to end): 41
Enter hourly rate of the employee ($00.00): 10.00
Salary is $415.00
"
#include <iostream>
using namespace std;
int main()
{
double salary=0,rate=0,hours=0,counter=0;
cout << "Enter your hours worked: ";
cin >> hours;
cout << "Enter your rate: ";
cin >> rate;
while(counter<=hours)
{ salary=hours*rate;
counter++;
}
if(hours==-1)
{exit(0);
}
else if(hours>=41)
{
rate = rate * 1.5;
salary = salary + rate;
}
cout << "$" << salary;
return 0;
}
The loop you used has no functionality related to the problem, so I omitted it. Below is what will work. As others have said, define why you need a loop. I'm guessing you need to loop the code so the user can repeat this to their heart's content. If that is the case, I'll let you try to figure out how to break out of the loop when a user enters -1.
if (hours == -1)
exit(0);
else if (hours <= 40)
salary = rate * hours;
else {
double overtimeHours = hours - 40;
salary = rate * 40;
rate = rate * 1.5;
salary = salary + (rate * overtimeHours);
}
cout << "$" << salary;
I have to display and loop a menu, allowing the customer to make multiple orders for peanuts, movies, or books. The menu displays fine, but the quantity doesn't go down to the calculations part of my code. Everytime I enter a quantity for anything and checkout it returns $0. I have no idea why this is happening I don't see anything wrong with my code, but obviously there is. Do you guys have any suggestions on what to do based on looking at what I have?
#include <iostream>
#include <cstdlib>
using namespace std;
//function declarations
void displayMenu();
//constant statements
const double BOOK_PRICE = 9.00; //price per book
const double BOOK_SHIPPING = 1.06; //shipping per book
const double MOVIE_PRICE = 13.99; //price per movie
const double MOVIE_SHIPPING = .05; //shipping per movie subtotal
const double PEANUT_PRICE = 1.80; //price of peanuts per pound
const double SHIPPING_PRICE = .50; //shipping of peanuts per lb
int main()
{
//declaration statements
int numBooks = 0; //# of books purchased
int numMovies = 0; //# of movies purchased
double numPeanuts = 0.0; //# of peanuts per pound
double bookSubtotal = 0.0; //subtotal of books
double movieSubtotal = 0.0; //subtotal of movies
double peanutSubtotal = 0.0; //subtotal of peanuts
int totalBooks = 0; //running total of books
int totalMovies = 0; //running total of movies
double totalPeanuts = 0.0; //running total of peanuts
int userChoice = 0; //user input
double totalPrice = 0.0; //final price
while (userChoice != 4)
{
displayMenu();
cout << "Enter a menu choice: ";
cin >> userChoice;
if (userChoice == 1)
{
cout << "Please enter the number of books: ";
cin >> numBooks;
totalBooks = totalBooks + numBooks;
}
else if (userChoice == 2)
{
cout << "Please enter the number of movies: ";
cin >> numMovies;
totalMovies = totalMovies + numMovies;
}
else if (userChoice == 3)
{
cout << "Please enter the pounds of peanuts as a decimal: ";
cin >> numPeanuts;
totalPeanuts = totalPeanuts + numPeanuts;
}
else if (userChoice == 4)
{
break;
}
else
{
cout << "Invalid Input" << endl;
}
}
//computations
bookSubtotal = (totalBooks * BOOK_PRICE) + (totalBooks * BOOK_SHIPPING);
movieSubtotal = (totalMovies * MOVIE_PRICE * .05) + (totalMovies * MOVIE_PRICE);
peanutSubtotal = (PEANUT_PRICE * totalPeanuts) + (totalPeanuts * .5);
totalPrice = bookSubtotal + movieSubtotal + peanutSubtotal;
cout << "The total price is $" << totalPrice << endl;
system("PAUSE");
return 0;
}//end of main
void displayMenu()
{
cout << "1 Books" << endl;
cout << "2 Movies" << endl;
cout << "3 Peanuts" << endl;
cout << "4 Checkout" << endl;
}//end of displayMenu
The problem is in the cin >> - you found the answer yourself when you say that the book count is zero. I suggest you try to put << endl after each cout << .... Other solution is to use _flushall(); after each cout.
I'm writing a program in Microsoft Visual Studio with C++ that will retrieve information from a .txt file. In that file there are negative numbers, but when I try to write a while loop that states what to do if there is a negative number, I get several errors.
Can someone please help me with this? Here is my code and I do realize there are errors but I can't figure out how to write the While loop statement to read these values which are hours worked and the hourly rate from the .txt file
Sample text file:
45.0 10.50
-35.0 7.75
50.0 12.00
45.0 -8.50
30.0 6.50
48.0 -10.25
-50.0 10.00
50.0 8.75
40.0 12.75
56.0 8.50
Code:
//*****************************
// This program is to help calculate an employee's weekly gross pay as well as
// the net pay while showing the taxes that were taken off.
// The data that will be shown will be calculated from a .txt file
// that was created and called employee.txt.
// Input: Will be the inFile known as employee.txt
// Output: Gross pay, taxable income, federal tax, state tax, and net pay
// Typed by:
// Date:
//******************************
#include <iomanip>
#include <fstream>
#include <iostream>
using namespace std;
float computeGross(float, float);
void computeTaxes(float, float&, float&, float&);
float computeNetPay (float&, float&, float&, float&);
const float hours = 40; // Regular 40 hour work week
const float ovTime = 1.5; // Overtime if hours go over 40
const float exemption = 200.0; // Exemption if pay goes over 200
const float fedTaxRate = 0.10; // Federal Tax Rate
const float stTaxRate = 0.03; // State Tax rate
ifstream inFile;
ofstream outFile;
int main()
{
inFile.open("employee.txt");
outFile.open("result.txt");
float hours, rate, grossPay, taxableIncome, fedTax, stTax, NetPay;
inFile >> hours >> rate;
while(inFile)
{
if {
(hours <= 0)&& (rate <= 0);
outFile << "Invalid Data";
}
else{
return 0;
}
}
grossPay = computeGross(hours, rate);
computeTaxes (grossPay, taxableIncome, fedTax, stTax);
computeNetPay (grossPay, fedTax, stTax, NetPay);
outFile << fixed << showpoint << setprecision(2);
outFile << "Hours worked = " << hours << endl
<< "Hourly rate = " << rate << endl
<< "Employee's gross pay = " << grossPay << endl
<< "Taxable Income = " << taxableIncome << endl
<< "Federal Taxes = " << fedTax << endl
<< "State Taxes = " << stTax << endl
<< "Net Pay = " << NetPay << endl;
return 0;
}
float computeGross (float h, float r) //Computes for the Gross Pay
{
if (h > hours)
return hours * r + (h - hours) * r * ovTime;
else
return h * r;
}
void computeTaxes(float g, float& taxable, float& fedTax, float& stTax) //Computes both Taxes
{
taxable = g - exemption;
if (taxable > 0.0)
{
fedTax = fedTaxRate * taxable;
stTax = stTaxRate * taxable;
}
else
{
fedTax = 0.0;
stTax = 0.0;
}
}
float computeNetPay (float& grossPay, float& fedTax, float& stTax, float& NetPay)
{
return NetPay = grossPay - fedTax - stTax;
}
In your main function you have:
while(inFile)
{
if ((hours <= 0) && (rate <= 0))
{
outFile << "Invalid Data";
}
else {
return 0;
}
}
When the else is triggered the program finishes, the main function returns. You might want a continue break or nothing here instead, that return statement ends the main function not the While loop.
To get all the data out of the file your read statement ( inFile >> hours >> rate);
will need to be in this or another loop. Say after the IF test for validity, it could be in the Else.
while(inFile)
{
if ((hours <= 0) && (rate <= 0)) {
outFile << "Invalid Data";
}
else {
// call the data functions
// save the returned values
}
//prime hours and rate for the next loop
inFile >> hours >> rate;
}
Well.. my guess is this is what your looking for:
Note that the:
if ((hours <= 0) && (rate <= 0))
is changed to:
if ((hours <= 0) || (rate <= 0))
otherwise it won't ever hit the "invalid data" with your supplied data
//*****************************
// This program is to help calculate an employee's weekly gross pay as well as
// the net pay while showing the taxes that were taken off.
// The data that will be shown will be calculated from a .txt file
// that was created and called employee.txt.
// Input: Will be the inFile known as employee.txt
// Output: Gross pay, taxable income, federal tax, state tax, and net pay
// Typed by:
// Date:
//******************************
#include <iomanip>
#include <fstream>
#include <iostream>
using namespace std;
float computeGross(float, float);
void computeTaxes(float, float&, float&, float&);
float computeNetPay (float&, float&, float&, float&);
const float hours = 40; // Regular 40 hour work week
const float ovTime = 1.5; // Overtime if hours go over 40
const float exemption = 200.0; // Exemption if pay goes over 200
const float fedTaxRate = 0.10; // Federal Tax Rate
const float stTaxRate = 0.03; // State Tax rate
int main()
{
ifstream inFile ("employee.txt");
ofstream outFile ("result.txt");
float hours, rate, grossPay, taxableIncome, fedTax, stTax, NetPay;
if (inFile.is_open())
{
while (! inFile.eof() )
{
inFile >> hours;
inFile >> rate;
if ((hours <= 0) || (rate <= 0))
{
outFile << "Invalid Data";
}
else
{
grossPay = computeGross(hours, rate);
computeTaxes (grossPay, taxableIncome, fedTax, stTax);
computeNetPay (grossPay, fedTax, stTax, NetPay);
outFile << fixed << showpoint << setprecision(2);
outFile << "Hours worked = " << hours << endl
<< "Hourly rate = " << rate << endl
<< "Employee's gross pay = " << grossPay << endl
<< "Taxable Income = " << taxableIncome << endl
<< "Federal Taxes = " << fedTax << endl
<< "State Taxes = " << stTax << endl
<< "Net Pay = " << NetPay << endl;
}
}
}
return 0;
}
The rest is the same
For a start, I think that this:
if {
(hours <= 0)&& (rate <= 0);
outFile << "Invalid Data";
}
Should be this:
if ((hours <= 0) && (rate <= 0)) {
outFile << "Invalid Data";
}
Note that to get code to format properly on StackOverflow, you should only use spaces, not tabs. I think that's whats causing your format issues.