It's the same in C as any language -- add up your values and divide by the number of values.
2007-12-06 15:37:34
·
answer #1
·
answered by mdigitale 7
·
0⤊
0⤋
You may wish to do a little more work on this, as it doesn't parse any user input. And realize that the sizeof operator is a compile time operation, not a runtime function. This means that sizeof(X) will only work if X has a set size at compile time. It won't work if the size of your array is determined by the user or somewhere else in the program. In that case, you'll need to keep track of the array size another way, such as by passing it into the function, or saving the array in a struct. Good Luck!
Also realize that you have the possibility of overflowing if the sum of the array exceeds the max value for a 32 bit float, in which case your result will print as INF. If this happens you can either convert your floats to doubles (where it may still happen) or try a rolling average method. You'll loose precision in the final answer since you take an average at every point, but you're almost guaranteed not to overflow.
int main(){
const float values[] = {1.0,2.0,3.0,3.14159 .... ETC FILL THIS IN ... , 1.234E17};
float sum = 0.0;
for(int i = 0; i < sizeof(values); i++){
sum+=values[i];
}
float avg = sum / sizeof(values);
printf("avg=%f\n", avg);
}
Or for the case of the rolling average method. There are more accurate ways to do the rolling average method, especially with power of two sized arrays, but this should work for now:
......
float avg = 0.0;
for(int i = 0; i < sizeof(values); i++){
if(i==0){
avg = values[i];
}else{
avg = avg * ((float)i/(float)(i+1)) + values[i] * (1.0/(i+1));
}
printf("avg=%f\n", avg);
}
printf("avg=%f\n", avg);
2007-12-06 19:10:48
·
answer #2
·
answered by Anonymous
·
0⤊
0⤋
Same as getting the average in any other language.
Sum the integers u require the average for (10+2+7+4)
Then divide by the number of integers (in this case 4)
=5.75
2007-12-06 15:38:00
·
answer #3
·
answered by Nasha 3
·
0⤊
0⤋
its your assignment? hehehe..you find answer in your c books..
2007-12-06 15:54:24
·
answer #4
·
answered by manski 1
·
0⤊
0⤋
(sum of all) / (number of items)
2007-12-06 15:43:53
·
answer #5
·
answered by Anonymous
·
0⤊
0⤋
its just all logic.
2007-12-06 15:38:17
·
answer #6
·
answered by jaypee A 2
·
0⤊
0⤋