Re: First Program
- From: Keith Thompson <kst-u@xxxxxxx>
- Date: Fri, 14 Apr 2006 01:38:48 GMT
"mwt" <michaeltaft@xxxxxxxxx> writes:
[...]
Here's a new function to compute the mean. In the main function, I've
precluded "0" as valid input in order to get around the divide by zero
problem. The cast to double in the return statement seems to be
necessary to make it work, but I don't know if this is the best way to
approach it.
double compute_mean(int *arr, int arr_length)
{
int j;
int total = 0;
for(j = 0; j < arr_length; j++)
{
total += arr[j];
}
return (double) total / arr_length;
}
Yes, this is one of the few cases where a cast is justified.
Without it (as you've probably seen), the expression "total / arr_length"
is evaluated as an int, which means the result is truncated. The "/"
operator takes two operands of the *same* numeric type, and yields a
result of the same type. Converting one operand to double forces the
other operand to be implicitly converted to double, yielding a double
result.
For the sake of symmetry, I might cast both operands:
return (double)total / (double)arr_length;
but it makes no real difference.
--
Keith Thompson (The_Other_Keith) kst-u@xxxxxxx <http://www.ghoti.net/~kst>
San Diego Supercomputer Center <*> <http://users.sdsc.edu/~kst>
We must do something. This is something. Therefore, we must do this.
.
- Follow-Ups:
- Re: First Program
- From: Micah Cowan
- Re: First Program
- References:
- First Program
- From: mwt
- Re: First Program
- From: Roberto Waltman
- Re: First Program
- From: Fred Kleinschmidt
- Re: First Program
- From: mwt
- First Program
- Prev by Date: Re: Source formatting
- Next by Date: Re: Incrementing a void pointer. Legal C99?
- Previous by thread: Re: First Program
- Next by thread: Re: First Program
- Index(es):
Relevant Pages
|