Complementary task for topic: 4

M Nemeth · 2023-08-29 15:21:04.619219'

Functions: Calculate Square Root

Functions: Calculate Square Root

Write a C function square_root that takes a positive floating-point number as input and returns its square root as a floating-point number. Use the built-in sqrt() function from the math.h library.

Hint:

Solution
#include 
#include 

// Function to calculate the square root
float square_root(float num) {
    if (num >= 0)
        return sqrt(num);
    else
        return -1.0; // Negative number indicates an error
}

int main() {
    float num;
    printf("Enter a positive number: ");
    scanf("%f", &num);

    float result = square_root(num);
    if (result >= 0)
        printf("The square root of %.2f is %.2f.\n", num, result);
    else
        printf("Error: Cannot calculate square root of a negative number.\n");

    return 0;
}



Explanation
The square_root function takes a positive number as input and returns its square root using the built-in sqrt() function from the math.h library. If the input number is negative, the function returns -1.0 as an error indicator. In the main function, the user is asked to input a positive number, and the square_root function is called to calculate and print the square root. If the input number is negative, an error message is displayed.
< < previous    next > >