"billcu34" <bill...@...> wrote:
> Varadha Rajan <vrajmca1887@> wrote:
> > ... try the following
#include <math.h>
> > double Sma(double *nums, int n)
const double *nums
Also, see previous threads for explanation of why n should be
of type size_t.
> > {
> > double total = 0;
> > int i;
> > for (i = 0; i < n; i++)
> > total *= nums[i];
> > return pow(total,double(1/n));
Firstly, Bill is writing in C; secondly, the cast is pointless
since the expression 1/n will be converted to a double if there
is a prototype for pow in scope. If there isn't a prototype
in scope, then pow will have the wrong default signature,
returning int instead of double in C89. Without a declaration
in scope, the code violates a constraint in C99.
Lastly, the associative rule does not apply to casts. In other
words, it won't convert 1 and n to doubles before doing the
division. Thus, even in C++, double(1/n) is not the same as
double(1)/double(n), rather it is just (double) (1/n).
Since n is an integer, if it is positive, then 1/n can only
yield 0 or 1. Not much point converting that to double.
> What exactly is the double in the pow() function for?
Losing marks?!
> If it's a cast doesn't it have to be in parenthesis?
In C, casts are of the form: (type-name) cast-expression.
Varadha Rajan is using a C++ cast. The form is actually
deprecated in C++ (though still in the standard.)
As is often the case, simpler options are better...
return pow(total, 1./n);
--
Peter