How to use the square root function in C language?

The function in C language for calculating square root is sqrt(), which is defined in the math.h header file.

The usage instructions are as follows:

  1. Include the math.h header file in the program: #include
  2. Call the sqrt() function where the square root function is needed and pass the number that needs to be square rooted as a parameter to the function, like:
  3. Calculate the square root of 16 and assign the result to the variable “result”.
  4. The sqrt() function returns a result of type double, so it needs to be stored in a double variable.

Important points to note:

  1. To find the square root of an integer, it is necessary to first convert the integer to a double type and then call the sqrt() function.
  2. If you request the square root of a negative number, the result will return as NaN (Not a Number).
  3. If an older C standard is being used, the math library needs to be linked at compile time by adding the parameter “-lm” to the compile command, such as gcc -o program program.c -lm. However, in newer C standards, the sqrt() function can be used directly without linking the math library.

Example code:

Include the standard input/output and math libraries.

In this code snippet, we are calculating the square root of 16 and then printing the result.

The output is: The square root of 16 is 4.000000.

广告
Closing in 10 seconds
bannerAds