Averages/Arithmetic mean: Difference between revisions

changed requirement regarding empty input, worded so it doesn't invalidate existing solutions; changed C example to *not* return 0 on such input.
(→‎{{header|ACL2}}: Returns 0 for the empty list even with guard checking enabled.)
(changed requirement regarding empty input, worded so it doesn't invalidate existing solutions; changed C example to *not* return 0 on such input.)
Line 1:
{{task|Probability and statistics}}Write a program to find the [[wp:arithmetic mean|mean]] (arithmetic average) of a numeric vector. TheIn programcase should work onof a zero-length vectorinput, (withsince the mean of an answerempty set of 0)numbers is ill-defined, the program may choose to behave in any way it deems appropriate, though if the programming language has an established convention for conveying math errors or undefined values, it's preferable to follow it.
 
See also: [[Median]], [[Mode]]
Line 296:
 
=={{header|C}}==
Compute mean of a <code>double</code> array of given length. If length is zero, does whatever <code>0/0</code> does (usually means returning <code>NaN</code>).
 
<lang c>#include <stdio.h>
This implementation uses a plain old static array of <tt>double</tt>s for the numeric vector.
 
double mean(double *pv, unsignedint qtylen)
<lang c>
#include <stdio.h>
 
/* Calculates the mean of qty doubles beginning at p. */
double mean(double *p, unsigned qty)
{
double int isum = 0;
int i;
double total = 0.0;
for (i = 0; i < qtylen; i++i)
 
total sum += pv[i];
if (qty == 0)
return totalsum / qtylen;
return 0;
 
for (i = 0; i < qty; ++i)
total += p[i];
return total / qty;
}
 
int main(void)
{
double testv[6] = {1.0, 2.0, 52.0718, -5.0, 9.53, 3.14159142};
int i, len;
for (len = 5; len >= 0; len--) {
printf("mean[");
for (i = 0; i < len; i++)
printf(i ? ", %g" : "%g", v[i]);
printf("] = %lgg\n", mean(testv, 6len));
}
 
return 0;
printf("%lg\n", mean(test, 6));
}</lang>{{out}}<pre>
return 0;
mean[1, 2, 2.718, 3, 3.142] = 2.372
mean[1, 2, 2.718, 3] = 2.1795
</lang>
mean[1, 2, 2.718] = 1.906
mean[1, 2] = 1.5
mean[1] = 1
mean[] = -nan
</langpre>
 
=={{header|C sharp}}==
Anonymous user