+ 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 ответов
+ 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
Solo Wanderer 4315
Solo Wanderer 4315 - 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
+ 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