Re: First Program



"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.
.



Relevant Pages

  • Re: unsigned right shift casts to int automatically!!!
    ... casts the data to int and extends it to int in unsigned form. ... Arithmetic operations with byte operands are required by the JLS to do ... "Binary numeric promotion is not performed on the operands; ... You can do an explicit cast followed by a mask to kill the sign extension: ...
    (comp.lang.java.programmer)
  • Re: Is cast operator unary or binary? How many operands?
    ... I'd say one operator, the cast operator, and two operands: ... cast is categorized as an unary operator. ... int i; /* cast i to int, a statement with no effect, or define i in ...
    (comp.lang.c)
  • Re: Give me an Int
    ... you can cast to an int only if it's already a ... numeric type, or an object representing a numeric type (that's what ... The cast ... and use casting for all numeric conversions. ...
    (microsoft.public.dotnet.languages.csharp)
  • Re: integer division
    ... > int i, pk, dy, dx, yc, xc, inc, temp; ... The fact that you cast the result afterwards does not change this. ... The int result, with no fractional part, will be converted to float ... If you convert either of the operands to float by a cast, ...
    (comp.lang.c)
  • Re: How to Retrieve a Numeric Type from a SqlServer table?
    ... casting to a double, and then cast that to int. ... > I am attempting to retrieve a numeric type froma a table. ... > SqlCommand cmdSelect; ...
    (microsoft.public.dotnet.languages.csharp)