Thursday, July 30, 2009

Why is this C++ code wrong?

It only caculates 90 regardless of the number of inputs





#include %26lt;iostream%26gt;


#include %26lt;iomanip%26gt;





using std::cout;


using std::cin;


using std::endl;


using std::setprecision;


using std::ios;


using std::setiosflags;





int main( )


{





//declare variables


int totalCharge = 0; //counter


int charge = 0; //accumulator


int reg = 0;


int totalReg = 0;


double avg = 0.0;





cout%26lt;%26lt; "Enter number of registrants: ";


cin%26gt;%26gt; reg;





while (reg %26gt;= 0)


{





if(reg %26lt;= 3)


charge = 150 * reg;





else if (reg = 4 || reg %26lt;= 9)


charge = 100 * reg;


else (reg %26gt;= 10);


charge = 90 * reg;





totalReg += reg;


totalCharge += charge;


avg = totalCharge /totalReg;


cout %26lt;%26lt; "Total Charge: $" %26lt;%26lt; totalCharge %26lt;%26lt; endl;


cout %26lt;%26lt; "Total Registrants: " %26lt;%26lt; totalReg%26lt;%26lt; endl;


cout %26lt;%26lt; "Total Average cost: $" %26lt;%26lt; avg %26lt;%26lt; endl;





cout%26lt;%26lt; "Enter number of registrants: ";


cin%26gt;%26gt; reg;


}


return 0;}

Why is this C++ code wrong?
Hi,





I think the problem is with this part of the code:





else (reg %26gt;= 10);


charge = 90 * reg;





It should be written like this:


else if (reg %26gt;= 10)


charge = 90 * reg;








You might ask why?


because the semecolon you put after the condition


(reg %26gt;= 10);


terminates the nested if else. then the statments that comes after that, which is:


charge = 90 * reg;


is executed regardless the number of registrants.





hope my answer is helpful, good luck.
Reply:your answer is incomplete I would like to point another error in the same program.


else if(reg=4||reg%26lt;=9) here (reg=4) is wrong becuase it is an assignment operator and not relational operator Report It



No comments:

Post a Comment