C pow function | Sololearn: Learn to code for FREE!
Новый курс! Каждый программист должен знать генеративный ИИ!
Попробуйте бесплатный урок
+ 1

C pow function

As we all know that 0.5 == 1/2 when I put the power of number "4" 0.5 the output will be 2 but when I put the power 1/2 the output will be 1 Actually I am solving my task using pow() and i want to make square root of numbers using pow function, instead of using sqrt() function https://code.sololearn.com/ccSGuLGIoXo3/?ref=app

7th Mar 2021, 9:58 AM
Abdul Moiz
Abdul Moiz - avatar
9 ответов
+ 7
1 and 2 are integers, so 1/2 == 0 with reminder of 1 NOT 0.5 To get the 0.5 at least one of the two operand must be a floating point number (1.0/2 or 1/2.0 etc.) also, sqrt uses a specialized algorithm for doing that particular operation, so it's more efficient and precise than using pow with a floating point number whitch is itself an approximation of 0.5
7th Mar 2021, 10:14 AM
Angelo
Angelo - avatar
+ 4
Abdul Moiz i am not sure about type conversion in c but from what i read just now it seems like int/int yields a int , i.e. 1/2==0 , if you want a float then you need to type cast one of those into float , i.e. (float)1/2 returns 0.5
7th Mar 2021, 10:12 AM
Abhay
Abhay - avatar
+ 2
i did, you already got the answer. why do more that doesn't work?
7th Mar 2021, 10:09 AM
Slick
Slick - avatar
+ 2
Thank you so much to all community for helping me I got the answer
7th Mar 2021, 10:23 AM
Abdul Moiz
Abdul Moiz - avatar
+ 1
The square root of 4 is 2 so it's right.
7th Mar 2021, 10:06 AM
Slick
Slick - avatar
+ 1
Please check the code Comment out put
7th Mar 2021, 10:07 AM
Abdul Moiz
Abdul Moiz - avatar
+ 1
Try 1.0/2 or 1/2.0 or 1.0/2.0 or (float)1/2 or 1/(float)2
7th Mar 2021, 10:28 AM
Sonic
Sonic - avatar
0
Because 1/2 == 0.5 The output of 0.5 is 2 But 1/2 is 1 Its a logical error
7th Mar 2021, 10:11 AM
Abdul Moiz
Abdul Moiz - avatar
0
Your question is already answered, but i want to add to Angelo that 0.5 is indeed an exact value in float. 0.5 = 1.0 * 2 ^ -1, this can be stored without approximation. For all other decimal digits, 0.x is approximated
7th Mar 2021, 10:58 AM
Benjamin Jürgens
Benjamin Jürgens - avatar