Home > Blockchain >  float value gives random value [duplicate]
float value gives random value [duplicate]

Time:09-16

#include <stdio.h>


float average(float arr[], int n)
{ 
  float sum ;
  for (int i = 0; i<n; i  ){
    sum = sum arr[i];
    
    printf("%p\n", arr i);
    printf("%f\n", arr[i]);
    printf("%f\n",sum );
  }
  return sum/n;

}

int main() {
  
    float arr1[5] = {1,2,3,4,5};
    printf("%f is the average.\n",average(arr1, 5));
  
  
    return 0;
}

Hello, I am learning c in school, and I encountered this weird situation. I want to write a function that gets an array of floats of length n and outputs the average of the numbers. and I am testing with two different text editors, one is VSC and repl.it online. I get

0x7ffe72970cc0
1.000000
1.000000
0x7ffe72970cc4
2.000000
3.000000
0x7ffe72970cc8
3.000000
6.000000
0x7ffe72970ccc
4.000000
10.000000
0x7ffe72970cd0
5.000000
15.000000
3.000000 is the average.

with repl.it, but when I use VSC, I get

0x7ffeeab1b770
1.000000
-107423728669532035777298432.000000
0x7ffeeab1b774
2.000000
-107423728669532035777298432.000000
0x7ffeeab1b778
3.000000
-107423728669532035777298432.000000
0x7ffeeab1b77c
4.000000
-107423728669532035777298432.000000
0x7ffeeab1b780
5.000000
-107423728669532035777298432.000000
-21484745272737805312720896.000000 is the average.

this. is there any wrong point in my code? why is it different between these two? I appreciate any feedback, thank you !

CodePudding user response:

You need to initialize the sum variable to zero when you declare it, like this:

float sum = 0;

A few more things:

You do not need array size if you are initializing it with values:

float arr1[5] = {1,2,3,4,5};

is equivalent to:

float arr1[] = {1, 2, 3, 4, 5};

And also, instead of passing 5 as array size, you can pass:

sizeof(arr1)/sizeof(float)

which will always be the correct size regardless of number of elements.

CodePudding user response:

In most C compilers, an uninitialized variable's value is garbage. When you say int x;, what it actually does it locate memory at some address. It does not do any kind of initializiation of the value of x, so x now contains some value that was there before (garbage).

It seems like repl.it is doing default initialization to 0; I don't recommend using this kind of compiler, because it prevents you from actually understanding how C works.

  • Related