mardi 14 septembre 2021

float value gives random value [duplicate]

#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 !




Aucun commentaire:

Enregistrer un commentaire