How to I find the square root of a number in C?
Printable View
How to I find the square root of a number in C?
Code:#include <math.h>
#include<stdio.h>
int main(void)
{
int x = 4;
int y = sqrt(x);
printf("%d",y);
return 0;
}
What compiler are you using? Check the math.h or any math related header file. There you will find a square root prototype. Us that function.
I'm using something called gcc
Govtcheez's example didn't work
The error message I got:
gcc -I/u1/pg/aramis/Lib/PI2/include -w -O2 -Dsolaris7 -Dsparc ./src/sq.c -L/u1/pg/aramis/Lib/PI2/lib/sparc-solaris7 -lPI2 -o ./bin/sq
Undefined first referenced
symbol in file
sqrt /var/tmp/cc6vnBFb.o
ld: fatal: Symbol referencing errors. No output written to ./bin/sq
collect2: ld returned 1 exit status
*** Error code 1
make: Fatal error: Command failed for target `conv'
His answer works fine in his compiler but it doesn't work on yours because you are probably using a different compiler, and you are also building files from the command line.
Add -lm to your command line: this library (libm) contains the math functions from math.h (and is not automagically linked, as many other compilers do). This should work if gcc is installed correctly:
gcc sq.c -lm
and it will create an executable a.out if there were no fatal errors, which you cat start by typing "./a.out" at the prompt
Hope this helps...
alex