芙蓉妹妹 - 云代码空间
——
#include<stdio.h> #include<stdlib.h> #include <time.h> #include "mpi.h" int main(int argc, char** argv){ MPI_Init(&argc, &argv); MPI_Comm comm = MPI_COMM_WORLD; int rank, size, part, *sbuf, *rbuf, num, i; double avge, sum, *aavge; MPI_Comm_rank(comm, &rank); MPI_Comm_size(comm, &size); MPI_Status status; num = 6; sbuf = (int*)malloc(sizeof(int)*num); if(rank == 0){ srand((unsigned)time(NULL)); for(i = 0; i < num; i++){ sbuf[i] = rand() % 20 + 1;//数字范围1~20 printf(" %d",sbuf[i]); } putchar('\n'); } part = num / size; rbuf = (int*)malloc(sizeof(int)*part); MPI_Scatter(sbuf,part,MPI_INT,rbuf,part,MPI_INT,0,comm); sum = 0; for(i = 0; i< part; i++) sum += rbuf[i]; avge = sum / part; printf("process %d :sum- %f, avge- %f.\n",rank,sum,avge); aavge = (double*)malloc(sizeof(double)*size); MPI_Gather(&avge,1,MPI_DOUBLE,aavge,1,MPI_DOUBLE,0,comm); if(rank == 0){ sum = 0; for(i = 1; i < size; i++){ sum += aavge[i]; } avge = sum / size; printf("The avge is %f\n",avge); } MPI_Finalize(); return 0; }