我正在创建一个程序来计算平均值和标准偏差以及打印数组。当我运行该程序时,我收到分段错误错误。
void printArray(int *array, int array_size){
for(int i = 0; i <array_size; i++){
std::cout<<array[i]<<", ";
if(i%10==9)
std::cout<<std::endl;
}
}
std::cout<<std::endl;
int sumArray(int *array, int array_size){
int sum = 0;
for(unsigned int i = 0; i < array_size; i++)
sum += array[i];
return sum;
}
float sumDifferences(int *array, int size, int average){
float sumDifference;
for(int i = 0; i<size; i++){
float differenceSquare = (array[i]-average)*(array[i]-average);
if(i==0)
sumDifference = differenceSquare;
else
sumDifference = sumDifference= differenceSquare;
}
return sumDifference;
}
double fRand(double min, double max){
double f = (double)rand() / RAND_MAX;
return min + f * (max - min);
}
void coordinator(int world_rank, int world_size){
int array_size = 100000;
int array[array_size];
int totalDiffSum;
int totalMean;
for(unsigned int i = 0; i <array_size; i++)
array[i]=fRand(0, 51);
int partition_size = array_size/world_size;
std::cout<<"coordinator rank 0 partition size is " <<partition_size << std::endl;
int *partition = new int[partition_size];
MPI_Bcast(&partition_size, 1, MPI_INT, 0, MPI_COMM_WORLD);
MPI_Scatter(array, partition_size, MPI_INT, partition, partition_size, MPI_INT, 0, MPI_COMM_WORLD);
int sum = sumArray(partition, partition_size);
int mean = sum / partition_size;
MPI_Reduce(&mean, &totalMean, 1, MPI_LONG_LONG_INT, MPI_SUM, 0, MPI_COMM_WORLD);
int average = totalMean / world_size;
MPI_Bcast(&average, 1, MPI_INT, 0, MPI_COMM_WORLD);
int sumDiff = sumDifferences(partition, partition_size, average);
MPI_Reduce(&sumDiff, &totalDiffSum, 1, MPI_LONG_LONG_INT, MPI_SUM, 0, MPI_COMM_WORLD);
double standardDeviation = sqrt(totalDiffSum / array_size);
printArray(array,array_size);
std::cout<<"Mean = "<<mean<<std::endl;
std::cout<<"Standard Deviation = "<<standardDeviation<<std::endl;
delete partition;
}
void participant(int world_rank,int world_size){
int partition_size = 0;
int totalMean;
int totalDiffSum;
int* array;
MPI_Bcast(&partition_size, 1, MPI_INT, 0, MPI_COMM_WORLD);
int *partition = new int[partition_size];
MPI_Scatter(&array, partition_size, MPI_INT, partition, partition_size,MPI_INT, 0, MPI_COMM_WORLD);
int sum = sumArray(partition, partition_size);
int mean = sum / partition_size;
MPI_Reduce(&mean, &totalMean, 1, MPI_LONG_LONG_INT, MPI_SUM, 0, MPI_COMM_WORLD);
int overallAverage = 0;
MPI_Bcast(&overallAverage, 1, MPI_INT, 0, MPI_COMM_WORLD);
int sumDiff = sumDifferences(partition, partition_size, overallAverage);
MPI_Reduce(&sumDiff, &totalDiffSum, 1, MPI_LONG_LONG_INT, MPI_SUM, 0, MPI_COMM_WORLD);
delete partition;
}
int main(int argc, char **argv){
MPI_Init(NULL,NULL);
int world_size,world_rank;
MPI_Comm_size(MPI_COMM_WORLD, &world_size);
MPI_Comm_rank(MPI_COMM_WORLD, &world_rank);
if(world_rank==0)
coordinator(world_rank,world_size);
else
participant(world_rank,world_size);
MPI_Finalize();
}
我在代码中看不到任何错误:
{{1}}
我非常感谢任何建议,因为我是c ++的新手,之前我从未遇到过这个错误。提前谢谢。