Shao Miller
5/28/2011 8:34:00 PM
On 5/28/2011 3:12 PM, Bill Cunningham wrote:
> pozz wrote:
>> Il 28/05/2011 21:28, Bill Cunningham ha scritto:
>>> void mean(double *avg, int periods)
>>> {
>>> double val;
>>> val = *avg / periods;
>>> printf("%.2f\n", val);
>>> }
>>
>> avg is a pointer to double. *avg is a double. If you write
>>
>> *avg / periods
>>
>> your dividing one double value by periods.
>>
>> In your case, avg points to an array of double values. The number of
>> elements in the array is periods. So you have to write a cycle to sum
>> all the periods elements together. At last, you can divide by periods.
>
> That's what I don't know how to do. Write a cycle. It's these little caveats
> in C that confuse me most. Functions I am grasping. Writing cycles not so
> much.
>
"A cycle" might also be called "a loop".
double mean(double * values, int periods) {
double accumulator;
int i;
double average;
accumulator = 0;
for (i = 0; i < periods; ++i)
accumulator += values[i];
average = accumulator / periods;
return average;
}
>>> int main(void)
>>> {
>>> double a[] = 2.2, 4.2, 5.00;
>> ^
>>
>> You are initializing an array. In C you can do that with curly
>> backets {}:
>> double a[] = { 2.2, 4.2, 5.00 };
>>
>>> mean(a, 3);
>> ^
>>
>> In this case you are passing the number of elements of a[] array. I
>> suggest to use a syntax like the following:
>>
>> mean(a, sizeof(a) / sizeof(a[0]));
>
> What's the sizeof(a[0]) mean?
Given:
double a[] = { 2.2, 4.2, 5.00 };
'sizeof a' yields the size of the 'a' array, in bytes. 'sizeof a[0]'
(or 'sizeof *a') gives the size of a single element of the 'a' array, in
bytes. Since a single element is a 'double' in this case, 'sizeof a[0]'
gives the same value as 'sizeof (double)'.
If you divide the size of the array by the size of one of its elements,
you get the number of elements in the array.
>
>> or define a generic macro if you're going to use this syntax in
>> several points:
>>
>> #define SIZEARRAY(a) (sizeof(a) / sizeof(a[0]))
>>
Thus, the above macro gives the number of elements in an array. Same
idea as:
#define COUNTOF(array) (sizeof (array) / sizeof *(array))