I am stuck in my project. I am actually finding the average of multiple values. I have ten values to average. The sum is giving the correct result for some time that is I am adding the negative numbers and the result is also negative numbers, but when the values whose average is to be found has high magnitudes then the 16bit register in which the summmation is stored gives positive value. What is going wrong in here.
void SmoothArray()
{
val = 0;
for(k=0;k<10;k++)
{
cc = array[k];
val += cc;
}
val /= 10;
}
In this when array has many locations negative the summation is wrong that is positive. C language used. Array is unsigned short, while val is short
OP's present code is overflowing.
Certainly using a wider integer is the simplest approach as answered by @ouah
Otherwise, to prevent overflow, consider summing in parts. Let us assume variables are type
int, int[]
This approach work well as long as the number of array elements (10 in OP's example) is less than
sqrt(INT_MAX)
.