w3resource

C sqrt() function

C sqrt() function - Calculate Square Root

Syntax:

double sqrt(double x)

The sqrt() function is used to calculate the nonnegative value of the square root of x.

Parameters:

Name Description Required /Optional
x Non-negative floating-point value Required

Return value from sqrt()

  • Returns the square root result.
  • Returns 0 if x is negative.

Example: sqrt() function

The following example shows the usage of sqrt() function.


#include <math.h>
#include <stdio.h>
#include <stdlib.h>

int main( void )
{
   double val = 66.34, result;
   result = sqrt( val );
   if( val < 0 )
      printf( "Error: sqrt returns %f\n", result );
   else
      printf( "The square root of %.2f is %.2f\n", val, result );
      
   val = -100;
   result = sqrt( val );
   if( val < 0 )
      printf( "\nError: sqrt returns %f\n", result );
   else
      printf( "\nThe square root of %.2f is %.2f\n", val, result );
}

Output:

The square root of 66.34 is 8.14

Error: sqrt returns -1.#IND00

C Programming Code Editor:

Previous C Programming: C pow()
Next C Programming: C ceil()



Follow us on Facebook and Twitter for latest update.

C Programming: Tips of the Day

What's the point of const pointers?

const is a tool which you should use in pursuit of a very important C++ concept:

Find bugs at compile-time, rather than run-time, by getting the compiler to enforce what you mean.

Even though it does not change the functionality, adding const generates a compiler error when you're doing things you didn't mean to do. Imagine the following typo:

void foo(int* ptr)
{
    ptr = 0;// oops, I meant *ptr = 0
}

If you use int* const, this would generate a compiler error because you're changing the value to ptr. Adding restrictions via syntax is a good thing in general. Just don't take it too far -- the example you gave is a case where most people don't bother using const.

Ref : https://bit.ly/33Cdn3Q