unable to use sqrt function directly | Sololearn: Learn to code for FREE!
New course! Every coder should learn Generative AI!
Try a free lesson
+ 5

unable to use sqrt function directly

I guess it might be to my poor knowledge in C, but I like to know why the sqrt function is not working directly in the print function like other functions https://code.sololearn.com/c31xJ730Odi2/?ref=app

28th Apr 2019, 1:14 PM
โœณAsterisKโœณ
โœณAsterisKโœณ - avatar
8 Answers
+ 10
Anyways adding (int) in front of your sqrt(i) outputs 3 to the console
28th Apr 2019, 1:24 PM
๐Ÿ‘‘ Prometheus ๐Ÿ‡ธ๐Ÿ‡ฌ
๐Ÿ‘‘ Prometheus ๐Ÿ‡ธ๐Ÿ‡ฌ - avatar
+ 10
PECHI MUTHU J You can. Look at the answers given by me, Zephyr and Kinshuk Vasisht.
28th Apr 2019, 1:34 PM
๐Ÿ‘‘ Prometheus ๐Ÿ‡ธ๐Ÿ‡ฌ
๐Ÿ‘‘ Prometheus ๐Ÿ‡ธ๐Ÿ‡ฌ - avatar
+ 7
The reason might be the incompatible types. sqrt() returns a double. What you use to print the result is the %d format specifier, which is used for signed integers. That is why the output is 0. If you try replacing that flag by %f or the format specifier for floats, you will get a correct result. printf("%d %f",j,sqrt(i)); Alternatively, casting the result to int in the call like this also prints the correct result: printf("%d %d",j,(int)sqrt(i));
28th Apr 2019, 1:23 PM
Kinshuk Vasisht
Kinshuk Vasisht - avatar
+ 7
In essence, the return type of the sqrt function is float. Therefore, you use %f to show the result. As for why that j works, type-casting should be the answer, I don't know what tinkering C does there.
28th Apr 2019, 1:24 PM
๐Ÿ‘‘ Prometheus ๐Ÿ‡ธ๐Ÿ‡ฌ
๐Ÿ‘‘ Prometheus ๐Ÿ‡ธ๐Ÿ‡ฌ - avatar
+ 6
In fact, square root computes a decimal number which returns a double data type. Therefore changing its data type to double and display with correct format specifier (i.e. %f) will do the job! ๐Ÿ˜‰
28th Apr 2019, 1:25 PM
Zephyr Koo
Zephyr Koo - avatar
28th Apr 2019, 1:22 PM
๐Ÿ‘‘ Prometheus ๐Ÿ‡ธ๐Ÿ‡ฌ
๐Ÿ‘‘ Prometheus ๐Ÿ‡ธ๐Ÿ‡ฌ - avatar
+ 1
We can't able to use the functions inside math.h library inside printf statement
28th Apr 2019, 1:30 PM
PECHI MUTHU J
PECHI MUTHU J - avatar
0
Yes we are able PECHI, the problem is that the function sqrt is not an integer ๐Ÿ˜’๐Ÿ˜’๐Ÿ˜’
28th Apr 2019, 3:58 PM
Werg Serium
Werg Serium - avatar