Tuesday, July 28, 2009

C++ Source code problems?

Can someone please check my code and tell me what I need to fix. I am beating my head on this one. Thanks





//this program displays the average hours worked





include %26lt;iostream%26gt;


using namespace std;





int main()


{


//declare and initialize variables


short region1Workers = 20;


short region2Workers = 10;


short region1Hours = 140;


short region2Hours = 125


short totalWorkers = 0;


short totalHours = 0;


float avgWorkerHours = (float) 0.0;








//calculate total workers, total hours, and average hours worked


totalWorkers = region1Workers + region2Workers;


totalHours = region1Hours + region2Hours;


avgWorkerHours = totalHours / totalWorkers;





//display average hours worked


cout %26gt;%26gt; "The average hours worked is " %26lt;%26lt; avgWorkerHours %26lt;%26lt; endl;





return 0;


} //end of main function

C++ Source code problems?
include %26lt;iostream%26gt;


1.you forgot the pound sign here #





short region2Hours = 125


2. forgot semi-colon here ;





cout %26gt;%26gt; "The average hours worked is " %26lt;%26lt; avgWorkerHours %26lt;%26lt; endl;


3. wrong operator used after cout. it should be stream insertion operator not extraction. %26lt;%26lt;





What compiler are you using? I recommend a you try using the debug function or using a compiler that gives helps you with error messages. The compiler helped me find all the syntax errors in a matter of seconds. I use MS visual c++ 6.0 its pretty old but still very good. Easier than gnu based debuggers in my opinion.
Reply:also note that avgWorkerHours is a float, but totalHours and totalWorkers are short. Your assignment is like this:





float = short / short





but a short-division does never return a float, but always as a short. - you have to cast:





avgWorkerHours = (float)totalHours / (float)totalWorkers;





now you get a float-division.


No comments:

Post a Comment