Friday, July 31, 2009

C++ biginner plz help.....?

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


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


void main()





{


float c;


c=400*400/400;


cout%26lt;%26lt;"output is "%26lt;%26lt;c;


getch();


}





ouput = 72





why not : 400

C++ biginner plz help.....?
I have the answer.





You should change the numbers to be "400.0" instead of "400". This is your primary problem.





The deeper reason that this is happening is that 400*400/400 is an INTEGER expression. It will be evaluated as an integer, and only assigned to a floating point result.





I believe that your compiler is a 16 bit compiler, this is the only answer that makes sense.





Now let's just see what the compiler is doing. Its first step is to evaluate 400*400. Now if you get out your calculator, you will get the answer 160,000. NOT SO FAST!!!! An integer in your compiler is only 16 bits long, and can only express numbers between -32768 and 32767. The answer that it comes up with is 28,928 (160,000 - 2*65,536). It will next divide 28,928 by 400 to give 72 (again it drops the fractional result because it is integer).





In both C and C++, the result of an integer expression is an integer. It does not matter if it gets assigned to a float or not. If you want float accuracy, then the numbers in the expression must be floats.
Reply:Sorry, it must be 400. '400*400/400' is an integer expression and evaluated as such. It is only changed to floating point when assigning the value to your float variable.





Do double check.
Reply:try to make : c= (400*400)/400;
Reply:please check by compiling again. it gives 400 on compilation.
Reply:i'm a biginner too but why do not initiate c with zero. try! and if is'nt that the problem don't bother me, please

aster

No comments:

Post a Comment