Tuesday, July 28, 2009

C ++ problem! can someone help me please!?

my program does not calculates correctly why?


i do a desk check with these amounts: 110.55, 203.45, and 100.68





this is my code:





#include %26lt;iostream%26gt;


#include %26lt;iomanip%26gt;





using std::cout;


using std::cin;


using std::fixed;


using std::endl;


using std::setprecision;





int main()


{


//declare variables


double region1Sales = 0.0;


double region2Sales = 0.0;


double region3Sales = 0.0;


int avgSales = 0.0;





//enter input items


cout %26lt;%26lt; "Enter region 1 sales: ";


cin %26gt;%26gt; region1Sales;


cout %26lt;%26lt; "Enter region 2 sales: ";


cin %26gt;%26gt; region2Sales;


cout %26lt;%26lt; "Enter region 3 sales: ";


cin %26gt;%26gt; region3Sales;





//calculate average sales


avgSales = region1Sales + region2Sales + region3Sales / 3;





//display average sales


cout %26lt;%26lt; "Average sales: " %26lt;%26lt; avgSales %26lt;%26lt; endl;


cin %26gt;%26gt; avgSales;


return 0;





} //end of main function

C ++ problem! can someone help me please!?
This line is incorrect:





avgSales = region1Sales + region2Sales + region3Sales / 3;





It should be:





avgSales = (region1Sales + region2Sales + region3Sales) / 3;





When doing mathematical operations, you must pay close attention to the hierarchy of mathematical operators. The multiplication and division (*,/) operators have a higher priority than addition and subtraction operators (+,-), and will be solved first.





So, what you have (as it is written) will do "region3Sales / 3" first, then will add region1Sales and region2Sales. By using parentheses, you can "force" all of the addition to occur first, then the multiplication, as in my correction.





Hope this helps. If so, please give me Best Answer.
Reply:yes
Reply:it is very simple you have not given bracket while calculating the avgSales


the code should be like this





avgSales = (region1Sales + region2Sales + region3Sales)/3.
Reply:avgSales = (region1Sales + region2Sales + region3Sales ) / 3;

marguerite

No comments:

Post a Comment