gpt4 book ai didi

MPI 中的 C++ double 类型

转载 作者:太空狗 更新时间:2023-10-29 20:56:05 25 4
gpt4 key购买 nike

我在 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 .

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

关于MPI 中的 C++ double 类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/34406572/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com