For some weird odd reason, sqrt(2/num) does not work.

cout << "   sqrt(2): " << sqrt(2) << endl;
			cout << "   sqrt(num): " << sqrt(num) << endl;
			cout << "   sqrt(2)/sqrt(num): " << sqrt(2)/sqrt(num) << endl;
			cout << "     sqrt(2/num): " << sqrt(2/num) << endl;

results in

sqrt(2): 1.41421
   sqrt(num): 2.82843
   sqrt(2)/sqrt(num): 0.5
     sqrt(2/num): 0

Can anybody tell me why? I am currently using sqrt(2)/sqrt(num) but I can't really think of a good reason why sqrt(2/num) shoudn't work..

9 Years
Discussion Span
Last Post by vmanes

sqrt() takes only floating point values as its argument, so I'm curious what compiler you're using that accepts the ints.

That said, the division 2/num (I'm assuming num is assigned value 8) results in value 0 (zero) being passed to sqrt( ).

Remember, the result of dividing one int by another will always be an int - no fractional part. So, to do what what you seem to be attempting:

cout << sqrt( double(2)/num );

will typecast the 2 to a double, num will be implicitly promoted as well, giving the value you expect.


I'm using gcc version 4.1.3 20070929 (prerelease) (Ubuntu 4.1.2-16ubuntu2)

Thanks for the tip, I did try casting double but I guess I typecasted double(2/num) instead of double(2)/num. Thanks again!


Well, that looks like another non-standard thing gcc has implemented.

Any gcc gurus care to chime in?

This question has already been answered. Start a new discussion instead.
Have something to contribute to this discussion? Please be thoughtful, detailed and courteous, and be sure to adhere to our posting rules.