Need help with my program that envolves functions.

Hello everybody,

This is my first program using functions. I believe I have an issue with returning, and sending values since my compute salary function gives initial values of zero.

Please help me understand what I did wrong,

Thank you

#include <iostream>
using namespace std;


double getHoursRate ( double hours , double rate , double ammount ) ;


double payCheck ( double hours , double rate ) ;

double Printcheck ( double hours , double rate , double ammount ) ;



int main ()
{

double rate=0;
double hours=0;

double ammount=0;

getHoursRate ( hours , rate , ammount ) ;



Printcheck ( hours , rate , ammount ) ;

system ( " pause " );

}




double getHoursRate (double hours , double rate , double ammount )


{
cout << "Please enter the number of hours worked " << endl;
cin >> hours ;

cout << "Please enter the rate of wage now " << endl;
cin >> rate;

payCheck ( hours , rate ) ;

return ammount ;
}


double payCheck (double hours , double rate )
{

double ammount =0 ;
double overpay =0 ;


if ( hours <= 40 )
{
ammount = hours * rate;
}
else
overpay= hours - 40;
ammount = (40 * rate ) + ( overpay * (rate * 1.5 ) ) ;


return ammount ;
}

double Printcheck ( double hours , double rate , double ammount )
{

cout << " You/employee has worked " << hours << endl;
cout << " Yours/employee's rate is " << rate << endl;
cout << " Your/employee's salary is " << ammount << endl;

return (0);
}


Let consider function getHoursRate.

Inside the function body you call another function payCheck. This function calculates amount and returns it. But inside function you do not use returned value of the amount. So the function payCheck was called in vain. It calculated the amount but you did not use it.

Let consider a simple example

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>

double f( double x )
{
   x = x + 10.0;
   return x;
}


int main()
{
   double x = 0.0;
   
   f( x );

   std::cout << "x = " << x << std::endl;
}

What value of x will be printed?

It is obvious that inside main the value of x will not be changed. So 0 will be printed.

But if you change the code inside main the following way

x = f( x );

then x get the value returned by f. And instead of 0 the new value that is 10 will be printed.

Another example


1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
#include <iostream>

double f( double &x )
{
   x = x + 10.0;
   return x;
}


int main()
{
   double x = 0.0;
   
   f( x );

   std::cout << "x = " << x << std::endl;
}


Here the function gets an argument by reference. So any changes of x inside the function will change the original x and 10 will be outputed.

Hope this halp you.
Last edited on
Topic archived. No new replies allowed.