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
#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
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.