Click to See Complete Forum and Search --> : sqrt
yawningdog
12-03-2003, 06:56 PM
I'm trying to get this function to work, but I must be missing something. Little help?
#include <stdio.h>
#include <math.h>
char line[100];
int square;
int root;
int main()
{
printf("Enter a number: ");
fgets(line, sizeof(line), stdin);
sscanf(line, "%d", &square);
root = sqrt(square);
printf("The square root of %d is %d.", square, root);
return(0);
}
saturn-vk
12-03-2003, 07:24 PM
and the error message is?
evac-q8r
12-03-2003, 10:45 PM
Hey yawningdog,
I think that your problem is the variable named root. First of all sqrt takes a double precision number and returns another double precision, i.e. a float. You have root defined as an integer. Secondly, it may be the name of the variable root. I remember once in my programming experiences that I named a window variable root because it was going to be the root window with a bunch of children windows associated with it and I simply changed the name of the variable to something different and then everything mysteriously became OK.
EVAC
Citadel
12-03-2003, 11:39 PM
Originally posted by yawningdog
I'm trying to get this function to work, but I must be missing something. Little help?
#include <stdio.h>
#include <math.h>
char line[100];
int square;
int root;
int main()
{
printf("Enter a number: ");
fgets(line, sizeof(line), stdin);
sscanf(line, "%d", &square);
root = sqrt(square);
printf("The square root of %d is %d.", square, root);
return(0);
}
Among other suggestions use the lm option:
gcc -lm program.c
yawningdog
12-04-2003, 06:34 PM
Cool, thanks. Changed the ints to floats and the ds to fs and all is go.
By the way, what's the -lm flag for?
bwkaz
12-04-2003, 08:01 PM
It requests that gcc link in its math library. The math library isn't linked by default, because it contains a whole bunch of functions that normally aren't used.
/lib/libm.so is the file, in case you're interested. Not that it's readable, though, except through nm or something. *shrug*
GlennaclawZ
12-09-2003, 08:48 PM
it is math.sqrt(int) try that there is also another command that is math.pow(num, power) as well to reverse it for future reference.
bwkaz
12-09-2003, 11:20 PM
In Java, perhaps (actually it's Math.sqrt(...) and Math.pow(x, y)).
But these functions don't even exist in C -- if you try to compile a program that says "math.sqrt" or "Math.sqrt" anywhere in it, you'll get errors about "undefined symbol math" or "undefined symbol Math", I think. I know it won't work.
;)