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
You will have undefined behavior. Let's say that for example your
intis 16-bit and you are adding the twointvalueINT_MINand-1, it will invoke undefined behavior. In most systems you will end up with a positive value.Use a variable of a wider type to sum your values, for example declare
valof typelongwhich guaranteed to be at least 32-bit wide.