delorie.com/archives/browse.cgi   search  
Mail Archives: djgpp/1997/06/12/01:45:15

From: "John M. Aldrich" <fighteer AT cs DOT com>
Newsgroups: comp.os.msdos.djgpp
Subject: Re: newbie math.h problem
Date: Sun, 08 Jun 1997 11:54:27 +0000
Organization: Two pounds of chaos and a pinch of salt
Lines: 59
Message-ID: <339A9D73.39AE@cs.com>
References: <339A8355 DOT 4CF6 AT glasgow DOT prestel DOT co DOT uk>
Reply-To: fighteer AT cs DOT com
NNTP-Posting-Host: ppp108.cs.com
Mime-Version: 1.0
To: djgpp AT delorie DOT com
DJ-Gateway: from newsgroup comp.os.msdos.djgpp

Michael Johnson wrote:
> 
> I've called the math.h lib and I get a SIGFPE error with what I think is
> a stack dump?  Any it will compile but not run.

Aha.  This post came later than your first one.  I think I have found
the problem; you are not initializing 'b' before passing it to the
sqrt() function.  There are two other errors as well:  you should use
'%f' to print floating point numbers, and main() must have a return
statement.  It should also be explicitly defined to return an integer.

If you had compiled with the '-Wall' and '-O' switches, those errors
would have been caught:

D:\CPROGS>gcc -Wall -O 3.c -o 3.exe -lm
3.c:5: warning: return-type defaults to `int'
3.c: In function `main':
3.c:8: warning: int format, double arg (arg 2)
3.c:8: warning: int format, double arg (arg 3)
3.c:6: warning: `b' might be used uninitialized in this function
3.c:9: warning: control reaches end of non-void function

> Here's what I've got:
> 
> #include <stdio.h>
> #include <math.h>
> 
> main()
> {
>   double b;
> 
>   printf("the square root of %d is %d\n",b,sqrt(b));
> }

Here's the correct code:

#include <stdio.h>
#include <math.h>

int main( void )  /* correct definition for main */
{
    double b = 3.1415296;  /* initialize b */

    /* use %f specifier to print doubles */
    printf( "The square root of %f is %f\n", b, sqrt( b ) );

    /* main must return an integer (0 means program succeeded) */
    return 0;
}

hth!

-- 
---------------------------------------------------------------------
| John M. Aldrich, aka Fighteer I  |     mailto:fighteer AT cs DOT com     |
|    *  Proud user of DJGPP!  *    |   http://www.cs.com/fighteer   |
|    ObJoke:  If Bill Gates were a robber, not only would he        |
|     shoot you, but he'd send you a bill for the bullets.          |
---------------------------------------------------------------------

- Raw text -


  webmaster     delorie software   privacy  
  Copyright © 2019   by DJ Delorie     Updated Jul 2019