C++: Calculations are incorrect when entering a certain input - c++

I've been teaching myself C++ on and off for a few months and now I'm trying to make a payroll system. Here's my code:
#include <iostream>
#include <cstdlib>
#include <string>
using namespace std;
void wageCompute (int, int);
int main()
{
int loopTimes=0;
int empNum=100, workHours, otHours, rate, bPay, otPay, grossPay;
string empName, empPos;
cout << "PAYROLL FOR THE MONTH OF MARCH" << endl;
cout << "Employees: " << empNum << endl;
while (empNum>loopTimes)
{
cout << "NAME: ";
cin.ignore();
getline (cin, empName);
cout << "\nPOSITION: ";
getline (cin, empPos);
cout << "\nHOURS WORKED: ";
cin >> workHours;
cout << "\nWAGE PER HOUR: ";
cin >> rate;
bPay = workHours*rate;
cout << "YOUR BASE PAY IS: " << bPay << endl << endl;
cout << "HOURS WORKED OVERTIME: ";
cin >> otHours;
otPay = (1.5*rate)*otHours;
cout << "\nOVERTIME PAY: " << otPay << endl;
grossPay = bPay + otPay;
cout << "GROSS PAY: " << grossPay << endl;
wageCompute(bPay, grossPay);
loopTimes++;
}
return EXIT_SUCCESS;
}
void wageCompute(int bPay, int grossPay)
{
double rate, dedInsurance, dedMedical, totDeduct, netPay, tax;
if (bPay<10001)
{
rate = 0.05;
}
else if (bPay<15001)
{
rate = 0.1;
}
else if (bPay<20001)
{
rate = 0.15;
}
else
{
rate = .2;
}
tax = bPay*rate;
dedInsurance = bPay*0.05;
dedMedical = bPay*0.01;
totDeduct = tax + dedInsurance + dedMedical;
cout << "TAX: " << tax << endl;
cout << "SSS DEDUCTION: " << dedInsurance << endl;
cout << "Medicare DEDUCTION: " << dedMedical << endl;
cout << "TOTAL DEDUCTIONS: " << totDeduct << endl;
netPay = grossPay - totDeduct;
cout << "NET PAY: " << netPay << endl;
}
The part where it goes wrong is when I input a certain value for the Hours Worked, Wage per Hour and Hours worked overtime. The program checks the basic pay for the suitable amount of tax it should deduct, what I input was 160 for the hours worked, 100 for the wage per hour, and 10 for overtime. I've tried lessening and increasing it and it worked just fine it seems that it's just these combination of numbers is the part where it goes wrong.
A screenshot of the output:

Your question isn't very clear but I suspect that what you are seeing here is a well known limitation of floating point numbers; numbers that are easy to represent exactly in base 10 don't have an exact representation in base 2. One example : 0.1 in base 10 is 0.0001100110011… repeating in base 2; the accuracy of the approximation depends on how many bits one is willing to use to write it.
An alternative approach is to use integer arithmetic with a known precision, so say you want to calculate to the nearest hundredth of a penny (I'm using UK currency here). Represent £1.01 as 10100 and when your finished val / 10000 is the pounds and (val % 10000) / 100 is the pence. If needed you can implement some more complex rules around rounding for the pence.

Related

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.

Why am I getting "Too few arguments to function"?

The code is to calculate the monthly payment of a car. Although I know I am not finished, I wish to see why I am not passing functions correctly.
#include <iostream>
#include <string>
#include <math.h>
using namespace std;
void instructions()
{
cout << "We will calculate the monthly payment for your particular car." << endl;
cout << "Please Follow the instructions." << endl;
}
string getCarType()
{
string carType;
cout << "Please enter the type of your car: " << endl;
cin >> carType;
return carType;
}
double getPurchasePrice()
{
double purchasePrice;
cout << "Please enter the price in which you purchased the vehicle: " << endl;
cin >> purchasePrice;
return purchasePrice;
}
double getDownPayment()
{
double downPayment;
cout << "Please enter the down payment made on the vehicle: " << endl;
cin >> downPayment;
return downPayment;
}
int getYears()
{
int years;
cout << "Please enter the number of years remaining to pay off the loan: " << endl;
cin >> years;
return years;
}
double getRate()
{
double rate;
double correctedRate;
cout << "Please enter the annual interest rate of the loan as a whole number: " << endl;
cin >> rate;
//calculations
correctedRate = (rate/100);
return correctedRate;
}
double findAmountFinanced(double &purchasePrice, double &downPayment)
{
double amountFinanced;
//calculations
amountFinanced = purchasePrice - downPayment;
return amountFinanced;
}
double findMonthlyPayment(double &amountFinanced, double &rate, int &years)
{
double monthlyPayment;
double sideOne;
double sideTwo;
//calculations
sideOne = amountFinanced * (rate/12);
sideTwo = pow(1 - (1 + (rate/12)) / (-12*years));
monthlyPayment = sideOne/sideTwo;
return monthlyPayment;
}
int findNumberOfPayments(int &years)
{
int payments;
payments = 12 * years;
return payments;
}
int main()
{
instructions();
string carType;
double purchasePrice;
double downPayment;
int years;
double rate;
double amountFinanced;
double monthlyPayment;
int payments;
carType = getCarType();
purchasePrice = getPurchasePrice();
downPayment = getDownPayment();
years = getYears();
rate = getRate();
monthlyPayment = findMonthlyPayment();
payments = findNumberOfPayments();
cout << "Make of car: " << carType << endl;
cout << "Price Purchased at: " << purchasePrice << endl;
cout << "Down payment made at purchase: " << downPayment << endl;
cout << "Years to pay off loan: " << years << endl;
cout << "Annual rate of interest: " << rate << endl;
cout << "Your monthly payment is: " << monthlyPayment << endl;
cout << "The total amount of payments is: " << payments << endl;
return 0;
}
Again, my error is that I have too few arguments to function.
In some of the functions like findMonthlyPayment you don't pass an argument from the main, whereas these functions expect arguments. You error is self-explanatory you should have debugged it yourself.
If you look at your method definitions for findAmountFinanced, findMonthlyPayment and findNumberOfPayments, they take arguments when they are called. In your main() function where you calling them, you are not passing any arguments. Hence, too few arguments :)
FYI, a trick to troubleshooting the issue is to look at the complete stack trace of the error message and work your way down through line numbers.
Yes, when you call a certain method and that method have X numbers of arguments or parameters, whenever you call that function in your program you need to call it with exactly the same number of arguments and type of arguments.

I want to use a variable from one function in multiple functions C++

Write a program a program that would compute the net salary of employees. The program should prompt the user to input number of hours worked and the hourly wage. Employees pay 17.5% of their gross salary as social security contribution. All employees pay 20% tax on their gross salary .Employees with gross salary less than 2500 pay 10% tax on their gross salary. Your program should use the following functions;
These are the instructions for the task. I have no problem writing the code, but I have trouble utilizing the grosspay variable in the necessary functions. Would really appreciate some help in modifying my code.
#include <iostream>
using namespace std;
double computeGross(double, double);
double computeDeductions(double);
void computeNet();
void validateHours();
void validateWage();
int main()
{
double hours, wage;
cout << "Please input the hourly wage of the employee. " << endl;
cin >> wage;
cout << "Please input the number of hours the employee worked." << endl;
cin >> hours;
computeGross(hours, wage);
computeDeductions(grosspay);
computeNet();
validateHours();
validateWage();
return 0;
}
double computeGross(double hours, double wage)
{
double grosspay = hours*wage;
cout << "The employee's gross pay is: " << " " << grosspay << endl;
}
double computeDeductions(double grosspay)
{
double total, sstotal, taxtotal;
double socialsecurity = .175;
double tax = .2;
double reducedtax = .1;
sstotal = grosspay*socialsecurity;
if (grosspay < 2500)
{
taxtotal = grosspay*reducedtax;
total = sstotal + taxtotal;
cout << "The total amount of deductions is: " << total << endl;
}
else
{
taxtotal = grosspay*tax;
total = sstotal + taxtotal;
cout << "The total amount of deductions is: " << total << endl;
}
}
void computeNet()
{
double netsalary;
netsalary = grosspay - deductions;
cout << "The net salary is: " << netsalary << endl;
cout << "The gross salary is: " << grosspay << endl;
cout << "The deductions total: " << deductions << endl;
}
void validateHours()
{
if (hours > 150 || hours < 0)
{
cout << "Invalid number of hours." << endl;
}
}
void validateWage()
{
if (wage > 200 || wage < 0)
{
cout << "Invalid wage." << endl;
return ;
}
}

Calculating Interest Rate

So I am trying to learn C++ for a college course and I have to write a program which uses this formula:
Amount = Principal * (1 + Rate/T)^T
Where principal is the balance in savings, rate is the interest rate, and t is the number of times the interest is compounded during a year. According to the book if you type in 4.25 as the interest rate and 12 as the number of times compounded with the principal as 1000.00 then you should get 43.34 as interest and the total amount should be 1043.34. I'm not sure if I am coding it wrong or what but I was wondering if anyone could help me out with any mistakes I might have done! I'm trying to do it on my own for about a day or two now but I have had no luck.
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
double PRINCIPAL;
double INTEREST_RATE;
double COMPOUND_AMOUNT;
cout << "What is your savings account balance?: " << endl;
cin >> PRINCIPAL;
cout << "What is your annual interest rate?: " << endl;
cin >> INTEREST_RATE;
cout << "How many times has your interest been compounded?: " << endl;
cin >> COMPOUND_AMOUNT;
double amt1 = 1 + (INTEREST_RATE/COMPOUND_AMOUNT);
double AMOUNT = PRINCIPAL * pow(amt1, COMPOUND_AMOUNT);
cout << "Interest Rate: " << INTEREST_RATE << endl;
cout << "Times Compounded: " << COMPOUND_AMOUNT << endl;
cout << "Principal: " << PRINCIPAL << endl;
cout << "Interest: " << INTEREST_RATE * COMPOUND_AMOUNT << endl;
cout << "Amount: " << AMOUNT << endl;
system("pause");
return 0;
}
This is a math error. If you're going to take in interest rates as '4.25' %, you need to divide the interest rate by 100. The code below gave me the amount as 1043.34 when 4.25 is entered as the interest rate.
#include <iostream>
#include <iomanip>
#include <cmath>
using namespace std;
int main()
{
double PRINCIPAL;
double INTEREST_RATE;
double COMPOUND_AMOUNT;
cout << "What is your savings account balance?: " << endl;
cin >> PRINCIPAL;
cout << "What is your annual interest rate? (in %): " << endl;
cin >> INTEREST_RATE;
INTEREST_RATE /= 100;
cout << "How many times has your interest been compounded?: " << endl;
cin >> COMPOUND_AMOUNT;
double amt1 = 1 + (INTEREST_RATE/COMPOUND_AMOUNT);
double AMOUNT = PRINCIPAL * pow(amt1, COMPOUND_AMOUNT);
cout << "Interest Rate (%): " << INTEREST_RATE * 100 << endl;
cout << "Times Compounded: " << COMPOUND_AMOUNT << endl;
cout << "Principal ($): " << PRINCIPAL << endl;
cout << "Interest ($): " << AMOUNT - PRINCIPAL << endl;
cout << "Amount ($): " << AMOUNT << endl;
system("pause");
return 0;
}
for interest your book is talking about the amount of interest in dollars, i.e. AMOUNT - PRINCIPAL.

C++ Program not reading formulas

My program I have been working on is supposed to output the following:
* The number of gallons of paint required
* The hours of labor required
* The cost of the paint
* The labor charges
* The total cost of the paint job
However, it displays 0 in every field.. What have I done wrong now?
Your help would be greatly appreciated.
Here is my code:
//Headers
#include <iostream>
#include <fstream>
#include <cmath>
#include <cstdlib>
#include <iomanip>
using namespace std;
void PaintJobEstimator(double gallonprice, double calc)
{
float numBucket=0;
float hours=0;
float bucketCost=0;
float laborCharges=0;
float totalCost=0;
//calculates number of buckets of paint (gallons) needed
numBucket=numBucket+calc*(1/115);
//calculates paint cost
bucketCost=bucketCost+gallonprice*numBucket;
//calculates labor hour
hours=hours+calc*(8/115);
//calculates labor charges
laborCharges=hours*18;
//calculates total cost
totalCost=totalCost+bucketCost+laborCharges;
//Console output
cout << "The number of Gallons of paint required:\t" << setprecision(2) << numBucket << endl;
cout << "The hours of labor required:\t" << setprecision(2) << hours << " hrs" << endl;
cout << "The labor charges:\t$" << setprecision(2) << laborCharges << endl;
cout << "The cost of the paint:\t$" << setprecision(2) << bucketCost << endl;
cout << "The total cost of the paint job:\t$" << setprecision(2) << totalCost << endl;
}
void main ()
{
int rooms;
double calc=0;
double wallspace;
double gallonprice;
cout << "=========================================================\n";
cout << "___________________Paint Job Estimator___________________\n";
cout << "_________________________________________________________\n";
cout << endl;
cout << "Enter the number of rooms: ";
cin >> rooms;
while (rooms<1) //validates rooms
{
cout << "Invalid entry, enter one or more rooms:\t";
cin >> rooms;
}
for (int roomNum=1;
roomNum<=rooms;
roomNum++)
{
cout << "Enter the wall space in square meters for room " << roomNum << ":\t" << endl;
cin >> wallspace;
while (wallspace < 0.01)//validates wallspace
{
cout << "Invalid entry, please re-enter the wall area for room " << roomNum << ":\t";
cin >> wallspace;
}
calc=calc+wallspace;
}//end loop
cout << "\nEnter price of the paint per gallon: ";
cin >> gallonprice;
if (gallonprice <10) //validates price per gallon
{
cout << "Invalid entry, Reenter price at a $10.00 minimum: ";
cin >> gallonprice;
}
PaintJobEstimator(gallonprice,wallspace);
system ("pause");
}
Here is a screenshot of the console:
You're multiplying by zero in some of the calculations. For example, in the following line of code:
numBucket=numBucket+calc*(1/115);
You put 1/115 in parenthesis, which evaluates to zero because of integer division. To achieve the desired effect, try:
numBucket = calc / 115.0f;