用户注册



邮箱:

密码:

用户登录


邮箱:

密码:
记住登录一个月忘记密码?

发表随想


还能输入:200字

芙蓉妹妹    -  云代码空间

——

MPI_Gather与MPI_Scatter计算平均值

2019-04-20|1389阅||

摘要:Genarate a random array of number on the root process(process 0). Scatter the number to all process, giving each process an equal amount of

#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;
}

1.生成随机数

#include<stdlib.h>
#include <time.h>
srand((unsigned)time(NULL));
a = rand() % 20 + 1;//数字范围1~20

2.输出

int  -     %d
double -%f 
          -%.2f  保留小数点后两位(数字是几,便保留几位)
          -%g 去掉小数点后多余的0,但如果原数是7.000,输出位7.0就很讨厌
char -    %c
string -  %s
顶 2踩 1收藏
文章评论
    发表评论

    个人资料

    • 昵称: 芙蓉妹妹
    • 等级: 资深程序员
    • 积分: 1710
    • 代码: 104 个
    • 文章: 25 篇
    • 随想: 0 条
    • 访问: 32 次
    • 关注

    标签

    最新提问

      站长推荐