芙蓉妹妹 - 云代码空间
——
#include<stdio.h> #include<math.h> #include "mpi.h" #define PI 3.14159265 int main(int argc, char** argv){ MPI_Init(&argc, &argv); MPI_Comm comm = MPI_COMM_WORLD; int rank, size, n = 9, k; MPI_Comm_rank(comm, &rank); MPI_Comm_size(comm, &size); MPI_Status status; double h = (PI*2)/size/n; double sum = 0; for(k = 0; k < n; k++) sum += h*cos((rank*n+k)*h +h /2); if(rank == 0){ printf("the sum of process %d is %f\n", rank, sum); double total = sum; for(k = 1; k < 4; k++){ MPI_Recv(&sum,1,MPI_DOUBLE,k,99,comm,&status); total += sum; } printf("f cos(x) dx is %f\n",total); } else{ MPI_Send(&sum,1,MPI_DOUBLE,0,99,comm); printf("%d sends to 0: %f\n", rank, sum); } MPI_Finalize(); return 0; }分成4部分积分,则size为4;n为每个part内分为几个小长方形