Tuesday, July 28, 2009

C++ code help?

I'm trying to do the area of triangle what am i missing error


error


In function `int main()':


expected `;' before "a"


In function `int main()':








using namespace std;





int main()


{





int a, b, c;


a = 2;


b = 3;


c = (1/2)a * b;


cout %26lt;%26lt; "the product of " %26lt;%26lt; a %26lt;%26lt; " and " %26lt;%26lt; b %26lt;%26lt; " is " %26lt;%26lt; c %26lt;%26lt; endl;





system ("pause");





return 0;


}

C++ code help?
Corrected version:





#include %26lt;iostream.h%26gt;





int main()


{


double a, b, c;


a = 2;


b = 3;


c = ((a * b) / 2);


cout %26lt;%26lt; "The area of triangle with width " %26lt;%26lt; a;


cout %26lt;%26lt; " and height " %26lt;%26lt; b %26lt;%26lt; " is " %26lt;%26lt; c %26lt;%26lt; endl;


system ("pause");


return 0;


}





What was wrong:





1. Integer division results in loss of precision. Use double to cater for an odd value of (a* b).





2.Integer divsion (1/2) is always zero in computer languages because no memory is allocated for the remainder. floats and doubles do carry remainders so use those for divisions in cases like these.





3. Program did not compile because (1/2)a*b is invalid syntax. You need to multiply a*b by a half which is the same as dividing a*b by 2. Better to use (a * b) / 2





4. Added include of iostream.h so that cout is recognised by compiler.





5. Added bracketing around calculation of c - always put brackets wherever you can. It helps the compiler avoid errors and makes it easier for you to see what is being calculated in what order.If you do not put brackets routinely, then the compiler may execute operations in an unintended order.





On the positive side , your calculation is correct -





A = bh / 2 where b = breadth and h = height.





http://www.mathgoodies.com/lessons/vol1/...
Reply:Carefully examine your syntax in this statement:





c = (1/2)a * b;





By the way, because you're multiplying by a fraction, using integer variables is a bad idea. What will happen if you had a=3 instead of a=2? In fact, depending on how your compiler works, the 1/2 may be evaluated as 0 or 1, not 0.5.





In fact, as I remember it, unless the triangle is a right triangle and the sides are the two short sides, the formula is wrong.





Also, a real nit as far as the execution goes, but an important one for programming style: since the three sides of a triangle are usually labelled a, b and c, using c for the area is not intuitive. Use something like "area".
Reply:c=(a/2)*b; ??





and seriously, this is bad coding....... what if int 'a' happens to be an odd number ?? a float or double would be more appropriate.


No comments:

Post a Comment