Mail Archives: djgpp/1996/12/12/23:41:58
A. Sinan Unur wrote:
>
> Murray Stokely wrote:
> > it seems sqrt is returning a realy
> > weird number
> ^^^^^
> no it is not.
>
> >
> > s=sqrt((double)(r*r) - (double)(m*m));
> > // also used pow(x,2) - same result
> > printf("%d\n",s); ^^^
You are attempting to print a double (8-byte floating point data)
as a 4-byte decimal integer.
> > // also used %i - same result
> >
> > r and m are integers (10 and 50), yet s keeps returning a huge
> > negative number (should be like 51 or something)
> >
> > Murray Stokely ( murray AT southeast DOT net )
>
> do you realize that 10*10 - 50*50 = -2400 and there is no real
> number whose square will give you -2400? you are feeding sqrt
> a totally invalid argument. GIGO (garbage-in-garbage-out).
<SNIP>
> the ansi standard states that "...a domain error occurs if the
> argument is negative." elsewhere, it states that "On a domain
> error, the function returns an implementation-defined value;
> the value of the macro EDOM is stored in errno.
The fact that he (Murray) got anything to print suggests to
me that what he posted was *not* what he compiled, since
sqrt()ing a negative number should cause a floating point
exception (at least it does on my machine), and unless he has
a handler for SIGFPE, his program would have crashed before
printing the "huge negative number" he described. I *suspect*
that he compiled:
s = sqrt((double)(r*r) + (double)(m*m));
^^^
Change the '-' to a '+', and fix the printf() statement and it
should work better. If you make both changes it should print:
50.990195
Here's the whole program with changes hi-lited
/********************* CUT HERE *******************/
#include <stdio.h>
#include <math.h>
int
main ()
{
double s;
int r;
int m;
r = 10;
m = 50;
s = sqrt((double)(r*r) + (double)(m*m));
/* ^^^ */
printf("%lf\n",s);
/* ^^^ */
return (0);
}
/********************* CUT HERE *******************/
Compile like this:
gxx -ofoo foo.cpp
Hope this helps.
--Phil Galbiati
=================================================
Any opinions expressed here reflect the
ignorance of the author, NOT Tektronix.
=================================================
- Raw text -