I participated in a recent contest, wherein I submitted this solution for the Multiplication table problem.
My solution passed the pretests but failed on a TC in system testing. In the failed TC, I was printing the square root of a perfect square and it was printed as 1e9 instead of 1000000000.
The square root function was not printing in scientific notation for smaller numbers, but it did for sqrt(1e18) i.e. 1e9. Does anyone know why this happened?
This behavior is due to cout rather than sqrt().
Why does this happen with cout? Do you know any reason for this?
cout by default outputs in scientific notation for large float numbers. Use
cout << fixed;
for fixed point notation.To overcome the problem you can typecast the result into long long , eg., typedef long long ll; ll n = 1e18; ll num = sqrt(n); cout << num << endl;
std::sqrt
returns a double, not an int. When numbers in doubles are printed, larger numbers are printed in scientific notation. To print it precisely, you have to typecast it into an int.Also, it is better to use
std::sqrtl
instead of sqrt, because sqrt sometimes fails with numbers upto $$$10^{18}$$$.Got it. Thanks!!
thanks!!