MPI中的C++双重类型

C++ double type in MPI

本文关键字:类型 C++ 中的 MPI      更新时间:2023-10-16

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 %dn", ridiculous);
    MPI_Send(&ridiculous, 1, MPI_DOUBLE, 1, 0, MPI_COMM_WORLD);
    printf("Process 0 sent number %dn", 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 0n", 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,请参阅此处的示例文档。

由于这个问题被标记为c++,所以您最好只使用iostreams进行输出。