Thursday, July 30, 2009

How would rewrite this C++ problem using VOID FUNCTIONS?

#include %26lt;iostream%26gt;


using namespace std;





//funtions prototypes


double getGross(int, double);


double getNet(double);





int main()


{


//declare variables


string name = "";


double rate = 0.0;


int hours = 0;


double grossPay = 0.0;


double netPay = 0.0;








//get input


cout %26lt;%26lt; "Enter employee's name: " %26lt;%26lt; endl;


getline (cin, name);


cout %26lt;%26lt; "Enter hours worked: " %26lt;%26lt; endl;


cin %26gt;%26gt; hours;


cout %26lt;%26lt; "Enter pay rate: " %26lt;%26lt; endl;


cin %26gt;%26gt; rate;








//function calls


grossPay = getGross(hours, rate);


netPay = getNet(grossPay);





//display information





cout %26lt;%26lt; "Employee Name: " %26lt;%26lt; name %26lt;%26lt; endl;


cout %26lt;%26lt; "Gross pay: " %26lt;%26lt; grossPay %26lt;%26lt; endl;


cout %26lt;%26lt; "Net pay: " %26lt;%26lt; netPay %26lt;%26lt; endl;


return 0;


}





//***PROGRAM DEFINED FUCTION***


double getGross (int hours, double rate)


{


double answer = 0.0;


answer = hours * rate;


return answer;





}

How would rewrite this C++ problem using VOID FUNCTIONS?
Alternatively, you could send a pointer to the function for it to store the value in. This would better maintain good OO principles like 'Information Hiding', 'Code Reuse' and 'Loose Coupling'.





For example if in the main routine instead of:


netPay = getNet(grossPay);


you would say


getNet(grossPay, %26amp;netPay);





and the getNet function would be:


void getNet (double grossPay, double *answer)


{


*answer = grossPay * .90;


}





Or better yet





inline void getNet(double grossPay, double *answer) {*answer = grossPay * .90;}
Reply:Above is a fine answer, and this syntax works just as well








void func( int param, int %26amp;answer);





int main(int c, char **argv)


{


int iParam = 1;


int answer;





func( param, answer);


}





void func( int param, int %26amp;answer)


{


answer = param;


}








I'm just not a fan of * because to me * means memory that I have to manage :)
Reply:In a void function, you would print the information during the function. That means that you'll need to move your cout statements for your gross pay and your net pay to their respective functions. That way you aren't returning anything because everything is done inside that function (the calculation AND the cout).





void getNet(double grossPay)


{


double answer = 0.0;


answer = grossPay * .90;


cout %26lt;%26lt; "Gross pay: " %26lt;%26lt; grossPay %26lt;%26lt; endl;


}


No comments:

Post a Comment