#include<stdio.h>
#include<stdlib.h>
#include<math.h>
#include<string.h>
#define MAX 100
void calc(float**, int, float*, float*);
int main( int argc, char* argv[] )
{
float *array[MAX];
float *MEAN;
float *SD;
int array_size, i;
array_size = argc;
for( i = 0; i < argc ; ++i )
{
*array = (float *) malloc( argc*(sizeof(float)));
*array[i] = atof(argv[i]);
}
calc(array, array_size, MEAN, SD);
return 0;
}
void calc(float* arr[] , int arr_size, float* mean, float* stdev)
{
int sum, i;
for ( i = 0; i < arr_size ; ++i )
{
sum += *arr[i];
}
*mean = sum / arr_size;
printf("%.2f", *mean);
for ( i = 0; i < arr_size ; ++i )
{
sum += pow((*arr[i]-*mean), 2);
}
*stdev = sqrt((sum/arr_size));
printf("%.2f", *stdev);
}
该代码应该确定许多用户输入的浮点数的平均值和标准偏差。尝试编译时,我不断遇到分段错误。我尝试释放 malloc,但它给代码带来了更多问题,所以我就让它保持原样——尽管它可能是内存分配的问题。
谢谢