MPI 中的 C++ 双精度类型

C++ double type in MPI

我在 MPI 中发生了一些奇怪的事情,我不太明白。我有以下简单代码:

MPI_Init(&argc, &argv);

int rank;
int size;

MPI_Comm_rank(MPI_COMM_WORLD, &rank);
MPI_Comm_size(MPI_COMM_WORLD, &size);

if (rank == 0) {
    double ridiculous = 7.9;

    printf("Process 0 will be sending number %d\n", ridiculous);

    MPI_Send(&ridiculous, 1, MPI_DOUBLE, 1, 0, MPI_COMM_WORLD);

    printf("Process 0 sent number %d\n", ridiculous);
}
else {
    double received = 0.;

    MPI_Recv(&received, 1, MPI_DOUBLE, 0, 0, MPI_COMM_WORLD,
        MPI_STATUS_IGNORE);

    printf("Process 1 received number %d from process 0\n", received);
}

MPI_Finalize();

我期望输出是这样的:

Process 0 will be sending number 7.9
Process 0 sent number 7.9
Process 1 received number 7.9 from process 0

却奇怪地收到了这个:

Process 0 will be sending number 1112261192
Process 0 sent number -32766
Process 1 received number -32766 from process 0

我不太擅长 MPI 的东西,但在我看来,double 类型出了点问题。因为如果我将 "double" 更改为 "int" 我会得到预期的输出:

Process 0 will be sending number 7
Process 0 sent number 7
Process 1 received number 7 from process 0

有什么建议吗?

您使用了错误的格式说明符,%d 用于 int。对于 double,您应该使用 %f%e%a%g,例如参见文档 here.

并且由于问题被标记为 ,您最好只使用 iostreams 进行输出。