15.7. sqrt()

Calculate the square root of a number

Prototypes

#include <math.h>
double sqrt(double x);
float sqrtf(float x);
long double sqrtl(long double x);

Description

Computes the square root of a number. To those of you who don't know what a square root is, I'm not going to explain. Suffice it to say, the square root of a number delivers a value that when squared (multiplied by itself) results in the original number.

Ok, fine--I did explain it after all, but only because I wanted to show off. It's not like I'm giving you examples or anything, such as the square root of nine is three, because when you multiply three by three you get nine, or anything like that. No examples. I hate examples!

And I suppose you wanted some actual practical information here as well. You can see the usual trio of functions here--they all compute square root, but they take different types as arguments. Pretty straightforward, really.

Return Value

Returns (and I know this must be something of a surprise to you) the square root of x. If you try to be smart and pass a negative number in for x, the global variable errno will be set to EDOM (which stands for DOMain Error, not some kind of cheese.)

Example

// example usage of sqrt()

float something = 10;

double x1 = 8.2, y1 = -5.4;
double x2 = 3.8, y2 = 34.9;
double dx, dy;

printf("square root of 10 is %.2f\n", sqrtf(something));

dx = x2 - x1;
dy = y2 - y1;
printf("distance between points (x1, y1) and (x2, y2): %.2f\n",
    sqrt(dx*dx + dy*dy));

And the output is:

square root of 10 is 3.16
distance between points (x1, y1) and (x2, y2): 40.54

See Also

hypot()