Martin McCormick wrote:
Most of the C programming I write manipulates strings so I haven't had
much experience with numerical functions and passing variables in and
out which brings me to a laughably simple problem that I am having.
How does one pass two unsigned longs in to a function that
will ultimately do floating point calculations on them?
A C tutorial I have says that one should not declare the
inputs to a function as floats but should use doubles which will
handle other numerical types. An example of what I am trying to do is:
void do_percent (lownum, highnum)
double lownum;
double highnum;
{ /*percentage routine*/
printf ("%.3f\n", (lownum/highnum));
return;
} /*percentage routine*/
There is no percentage arithmetic in it yet because if I call
it like:
do_percent (smallnumber, largenumber); with both the input arguments
being unsigned long numbers, the two values become corrupt when doing a
gdb trace.
That's because do_percent() expects to receive two
`double' values, but you've passed it two `unsigned long'
values instead. The traffic cop asked you for your license
and you handed him a codfish; is it any surprise that you're
in trouble? Write
do_percent( (double)smallnumber, (double)largenumber );
A far better solution is to get a more recent tutorial,
one that's been written less than a decade and a half ago.
Then you'd learn that the way you've written the function is
old-hat, and that a newer and better way has been available
since 1989:
void do_percent(double lownum, double highnum)
{
printf ("%.3f", lownum / highnum);
}
This do_percent() function, like the original, requires two
`double' arguments. However, this manner of defining the
function also "advertises" the number and nature of its
arguments so the compiler can generate whatever conversions
are necessary between what you supply and what do_percent()
expects (or can complain if what you supply can't be converted
to `double').
Since your tutorial apparently knows about `void' (which
came into the language at the same time as the newer function
style), it should tell you that the old style shown above is
kept around only for compatibility with pre-1989 C and that
you should use the new style for practically all new code.
Look up the word "prototype" in the index -- and if it's not
there, get yourself a newer tutorial.
--
Er*********@sun.com