Thread: square root

  1. #1
    help
    Guest

    square root

    How to I find the square root of a number in C?

  2. #2
    Mayor of Awesometown Govtcheez's Avatar
    Join Date
    Aug 2001
    Location
    MI
    Posts
    8,823
    Code:
    #include <math.h>
    #include<stdio.h>
    int main(void)
    {
       int x = 4;
       int y = sqrt(x);
       printf("%d",y);
       return 0;
    }

  3. #3
    Anti-Terrorist
    Join Date
    Aug 2001
    Location
    mming, Game DevelopmentCSR >&<>&2Minimization of boolean functions, PROM,PLA design >&0>&WA, USA guitar, dogsCommercial Aviation >&>>&USAProgramming
    Posts
    742
    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 compile code with:
    Visual Studio.NET beta2

  4. #4
    help
    Guest
    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'

  5. #5
    Anti-Terrorist
    Join Date
    Aug 2001
    Location
    mming, Game DevelopmentCSR >&<>&2Minimization of boolean functions, PROM,PLA design >&0>&WA, USA guitar, dogsCommercial Aviation >&>>&USAProgramming
    Posts
    742
    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.
    I compile code with:
    Visual Studio.NET beta2

  6. #6
    alex
    Guest
    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

Popular pages Recent additions subscribe to a feed

Similar Threads

  1. program to calculate the square root
    By saszew in forum C Programming
    Replies: 7
    Last Post: 10-28-2008, 12:53 PM
  2. Forced moves trouble!!
    By Zishaan in forum Game Programming
    Replies: 0
    Last Post: 03-27-2007, 06:57 PM
  3. Bisection Method function value at root incorrect
    By mr_glass in forum C Programming
    Replies: 3
    Last Post: 11-10-2005, 09:10 AM
  4. Square Root ?!?
    By Tm687 in forum C++ Programming
    Replies: 1
    Last Post: 02-29-2004, 04:38 PM
  5. Templated Binary Tree... dear god...
    By Nakeerb in forum C++ Programming
    Replies: 15
    Last Post: 01-17-2003, 02:24 AM