Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Array giving different outputs in C?

Tags:

arrays

c

Every time I execute my program which finds the average in a ten element array. I get slightly different results. Any idea why?

Here is my code:

#include "stdio.h"

int main()
{
float array[10];

for (int n=0; n<10;n++)
{
    array[n] = n * 4.76;
    printf("array[%i] = %.4f\n",n,array[n] );
}

float total;
for (int n=0; n<10; n++)
{
    total = total + array[n];
}

printf("Average: %.4f\n", total/10 );
return 0;
}

and some sample results are:

array[0] = 0.0000
array[1] = 4.7600
array[2] = 9.5200
array[3] = 14.2800
array[4] = 19.0400
array[5] = 23.8000
array[6] = 28.5600
array[7] = 33.3200
array[8] = 38.0800
array[9] = 42.8400
Average: 21.2598

array[0] = 0.0000
array[1] = 4.7600
array[2] = 9.5200
array[3] = 14.2800
array[4] = 19.0400
array[5] = 23.8000
array[6] = 28.5600
array[7] = 33.3200
array[8] = 38.0800
array[9] = 42.8400
Average: 21.2826

1 Answers

When declaring variables in C, make sure they're initialised to a default value. Variables allocated on the stack are usually not initialised to their default values, rather, they are initialised with junk.

So, before starting summation, initialise your variable as

float total = 0.0f;

and you should get the same answer every time.

like image 128
cs95 Avatar answered May 02 '26 09:05

cs95



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!