Pass By Reference, Getting Incorrect Answer in C++ - c++

This is a simple Pass By Reference Problem to calculate the salary after tax, when directly printing "income-income*tax" it's giving the expected output but when the value of variable is updated it's giving a wrong answer.
It is working fine in the online compiler.
What could be the reason of this?
// Using Reference Variable
#include<iostream>
using namespace std;
void incomeAfterTax(int &income)
{
float tax = 0.10;
cout << income-income*tax << endl; // printing 90
income = income - income*tax;
cout << income << endl; // but here it is 89
}
int main()
{
int salary = 100;
cout << "Total Salary: " << salary << endl;
incomeAfterTax(salary);
cout << "Income After Tax: " << salary; // prints 89
return 0;
}

This is probably a floating point issue; were the result of 'income-tax' is being converted to an integer.
The issue is avoidable by using the round() function in (for C++11). (roundf() if using C99)
#include<iostream>
#include <cstdint>
#include<cmath>
using namespace std;
void incomeAfterTax(int& income)
{
const float tax = 0.10;
cout << income-income*tax << endl;
const float tax_amt = static_cast<float>(income) * tax; // income is int, cast to float
income -= round(tax_amt); //round the float value to closest int
cout << income << endl;
}
int main()
{
int salary = 100;
cout << "Total Salary: " << salary << endl;
incomeAfterTax(salary);
cout << "Income After Tax: " << salary;
return 0;
}

Related

C++ Passing a variable to another function

int samuelt1(){
ela = 80;
socials = 80;
total = ela + socials;
int grade = total / 11.5;
cout << "Samuel's grade average for term 1 is: " << grade << "%" << endl;
cout << "Individual Subjects: " << endl;
cout << "ELA: " << ela << endl;
cout << "Socials: " << socials << endl;
return grade;
}
int average(){
int avg = [samuelt1's grade??] / 1;
cout << avg;
return 0;
}
I'd like to pass the grade variable over to the average function; is there a way to do that? Thanks!
In the main function, store the value returned by the function samuelt1 in the variable Grade. Pass Grade as a parameter to the function average, like so
#include <iostream>
using namespace std;
int samuelt1(){
int ela = 80;
int socials = 80;
int total = ela + socials;
int grade = total / 11.5;
cout << "Samuel's grade average for term 1 is : " << grade << "%" << endl;
cout << "Individual Subjects : " << endl;
cout << "ELA : " << ela << endl;
cout << "Socials : " << socials << endl;
return grade;
}
int average(int grade){
int avg = grade / 1;
cout << "Average : " << avg;
return 0;
}
int main(){
int Grade = samuelt1();
average(Grade);
}
In C++, as in most languages, functions can be created to accept parameters and/or return values. To do this, you just need to specify a type and a name inside the parenthesis. Here is an example:
void printGrade(int grade)
{
cout << grade << endl;
}
int main()
{
int grade = 10;
printGrade(grade);
}
Running that program will print 10 to the screen. One thing to note is that when you pass in an integer parameter, the computer is just creating a copy of the value. This means the original grade variable is not changed or affected. Consider this example:
void printGrade(int grade)
{
cout << grade << endl;
grade = 15;
}
int main()
{
int grade = 10;
printGrade(grade);
cout << grade << endl;
}
You may expect this program to print 10, followed by 15. Since a copy of value is created inside the printGrade() function, the value of grade is affected only inside the scope of the printGrade() function. If you need to change the original value inside the printGrade() function, then you must pass the parameters by reference. Here is an example:
void printGrade(int &grade)
{
cout << grade << endl;
grade = 15;
}
int main()
{
int grade = 10;
printGrade(grade);
cout << grade << endl;
}
You'll notice in this example, the variable name is preceded with an ampersand. This tells the computer that you want to pass a reference to the grade variable to the function rather than making a copy.
Hopefully this all makes sense!

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

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

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.

C++ Programming - Calculating recurrent increases

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