Calculate Square Root in C: sqrt() Guide

In the C language, you can use the sqrt() function to calculate the square root of a number. This function is defined in the header file. Here is an example code:

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

int main() {
    double num, squareRoot;

    printf("请输入一个数: ");
    scanf("%lf", &num);

    // 计算平方根
    squareRoot = sqrt(num);

    printf("平方根为: %.2lf\n", squareRoot);

    return 0;
}

In the above code, begin by adding the and header files. Next, declare a double-type variable called “num” to store the user input number, and declare another double-type variable called “squareRoot” to store the calculated square root.

Next, prompt the user to enter a number using the printf() function and assign the number entered by the user to the num variable using the scanf() function.

Next, calculate the square root of num using the sqrt() function and assign the result to the variable squareRoot.

Finally, use the printf() function to display the calculated square root on the screen.

Please note that the parameters and return value of the sqrt() function are both of type double, so make sure to use double variables to store them. You can use %.2lf to control the number of decimal places in the output.

bannerAds