芙蓉妹妹 - 云代码空间
——
#include<stdio.h> #include "mpi.h" int main(int argc, char** argv){ MPI_Init(&argc, &argv); MPI_Comm comm = MPI_COMM_WORLD; int rank, size, max, mmax, start, end, avge, *data, num, i; MPI_Comm_rank(comm, &rank); MPI_Comm_size(comm, &size); MPI_Status status; if(rank == 0){ printf("please input the num of data :\n"); scanf("%d",&num); for(i = 1; i < size; i++) MPI_Send(&num,1,MPI_INT,i,99,comm); data = (int*)malloc(sizeof(int)*num); for(i = 0; i < num; i++) scanf("%d",&data[i]); for(i = 1; i < size; i++) MPI_Send(data,num,MPI_INT,i,99,comm); } else{ MPI_Recv(&num,1,MPI_INT,0,99,comm,&status); //printf("process %d recv %d from process 0\n",rank,num); data = (int*)malloc(sizeof(int)*num); MPI_Recv(data,num,MPI_INT,0,99,comm,&status); //printf("process %d recv data from process 0\n",rank); } avge = num / size; start = rank * avge; end = rank == size - 1? num - 1: start + avge - 1; max = data[start]; for(i = start; i<= end; i++){ if(data[i] > max) max = data[i]; } printf("process %d :start- %d , end- %d ,max- %d.\n",rank,start, end,max); if(rank == 0){ mmax = max; for(i = 1; i < size; i++){ MPI_Recv(&max,1,MPI_INT,i,99,comm,&status); //printf("process 0 recv max from process %d\n",i); if(max > mmax) mmax = max; } printf("The max is %d\n",mmax); } else{ MPI_Send(&max,1,MPI_INT,0,99,comm); //printf("process %d send %d to process 0\n", rank,max); } MPI_Finalize(); return 0; }前一个代码每个if句里有重负的计算最大值的代码,这次尝试放到外面,成功执行