// MPI1.cpp : 定义控制台应用程序的入口点。
//

#include "stdafx.h"
#include "mpi.h"
#include <Windows.h>
#include <stdio.h>
#include <math.h>


int main(int argc, char* argv[])
{
	int done=0,n,myid,numproces,i;
	double mypi,pi,sum;
	double startwtime,endwtime;
	int namelen;
	char processor_name[MPI_MAX_PROCESSOR_NAME];
	MPI_Init(&argc,&argv);
	MPI_Comm_rank(MPI_COMM_WORLD,&myid);
	MPI_Comm_size(MPI_COMM_WORLD,&numproces);
	MPI_Get_processor_name(processor_name,&namelen);
	fprintf(stderr,"Process %d on %s\n",myid,processor_name);
	fflush(stderr);

	n=0;
	while(!done)
	{
		if(myid==0)
		{
			printf("输入一个数字不超过:(0退出)");
			fflush(stdout);
			scanf_s("%d",&n);
			startwtime=MPI_Wtime();
		}
		MPI_Bcast(&n,1,MPI_INT,0,MPI_COMM_WORLD);
		if(n==0)
			done=1;
		else
		{
			sum=0.0;
			for(i=myid+1;i<=n;i+=numproces)
				sum+=i;
			mypi=sum;
			MPI_Reduce(&mypi,&pi,1,MPI_DOUBLE,MPI_SUM,0,MPI_COMM_WORLD);
			if(myid==0)
			{
				printf("结果%.16f\n",pi);
				endwtime=MPI_Wtime();
				printf("时间=%f\n",endwtime-startwtime);
			}
		}
	}
	MPI_Finalize;
	printf("时间");
	system("pause");
	return 0;
}

运行结果如下: