In this source code example, we will see how to use the sqrt() function in C programming with an example.
sqrt() Function Overview
The sqrt() function in C computes the square root of a given number. It's an essential function in various mathematical, engineering, and scientific computations. The function is available in the math.h library.
Key Points:
- Make sure to include the math.h header to access the sqrt() function.
- The function is designed to find the non-negative square root of a number.
- If the provided argument is negative, the function will return a domain error.
- Always remember to link the math library using the -lm flag when compiling.
Source Code Example
#include <stdio.h> #include <math.h> // Necessary for sqrt() int main() { double value, result; // Ask for user input printf("Enter a non-negative value to compute its square root: "); scanf("%lf", &value); if(value < 0) { printf("Error: Input should be non-negative.\n"); return 1; } // Compute the square root of the given value result = sqrt(value); // Display the result printf("Square root of %.2lf is: %.2lf\n", value, result); return 0; }
Output
Enter a non-negative value to compute its square root: 4 Square root of 4.00 is: 2.00
Explanation
1. We initiate by including the required header files: stdio.h for basic input/output operations and math.h for the sqrt() function.
2. In the main() function, we prompt the user to input a value.
3. A condition checks if the entered value is non-negative. If not, an error message is shown, and the program terminates.
4. If a non-negative value is provided, the sqrt() function calculates its square root.
5. The computed result is then displayed on the console.
Comments
Post a Comment