Tuesday, July 14, 2009

Help on c++?

I wrote a program that compute %26amp; print the Area of triangle :


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


main( )


{


const 1/2;


int b,h;


cout%26lt;%26lt;"enter b,h"%26lt;%26lt;endl;


cin%26gt;%26gt;b;


cin%26gt;%26gt;h;


cout%26lt;%26lt;"Area of Triangle="%26lt;%26lt;1/2*b*h;


}





please can any one tell me what's wrong with it .

Help on c++?
1) Remove const 1/2


2) Write b*h*1/2 instead of 1/2*b*h while printing





Your program will run











The MAIN REASON your program isn't giving right answer is you are printing 1/2*b*h. As the compiler reads from left to right and as the priority of '/' and '*' is equal, so it is taking this expression as 1/(2*b*h).





As you haven't mentioned any data type for the answer, compiler is treating it as an integer output. As 2*b*h becomes a large value, 1/(2*b*h) becomes zero (0). So your output is 0.
Reply:First remove const 1/2


It doesnt make sense





Now... since u are using 1/2.. it is a floating point value.


So just add this statement:





float area = 0.5 * b * h;


cout %26lt;%26lt; "Area of Triangle = " %26lt;%26lt; area;





Thats it ;)
Reply:It will give you error at


const 1/2


Sicne C++ does not allow "/" operator in the declaration of Const. If at all you are interested in so, try to use


() in the const declaration.


But I dont see any other error apart from this in the above code.


No comments:

Post a Comment