我是c ++的新手,也是MPI的新手,所以我遇到了一些问题。
在我的代码中,进程0读取文本文件(burcu-名称文件,字母-所有字母),并将名称文件转换为数字数组。通过MPI_Bcast,我将字母的数量分配给不同的进程,这些从属进程进行一些算术运算。最后,通过使用MPI_Reduce,我将这些算术运算(xnum)的结果收集到进程0的weightednum中。
问题是当我运行代码时,尽管xnum值正确,但是weightednum的结果很奇怪,如939605(应该是215,这是xnum的总和)。错误结果的原因可能是什么?我的代码如下:
int main (int argc, char **argv) {
int myid, nprocs;
int *countname, xnum, weightednum;
char *burcu, *alfabe;
MPI_Init (&argc, &argv);
MPI_Comm_rank (MPI_COMM_WORLD, &myid);
MPI_Comm_size (MPI_COMM_WORLD, &nprocs);
int size = 5;
countname = new int[size];
burcu = new char[5];
alfabe = new char[26];
char name[5];
char alphabet[26];
MPI_Reduce(&xnum, &weightednum, 1, MPI_INT, MPI_SUM, 0, MPI_COMM_WORLD);
if (myid == 0) {
cout << "wn" << weightednum ;
// Read myname.txt file and convert it to a string
ifstream input("myname.txt");
for (int i = 1; i < 6; i++){
input >> name;
cout << name;
burcu[i] = *name;
}
// Read alhabet.txt file and convert it to a string
ifstream input1("alphabet.txt");
for (int i = 1; i < 27; i++){
input1 >> alphabet;
cout << alphabet;
alfabe[i] = *alphabet;
}
for (int i = 1; i <= 5; i++){
for (int j = 1; j<= 26; j++){
if (alfabe[j] == burcu[i]){
countname[i] = j;
break;
}
}
cout << countname[i] << " ";
}
input.close();
input1.close();
}
// Send name and alphabet strings to all processors by means of broadcasting
MPI_Bcast(countname, 6, MPI_INT, 0, MPI_COMM_WORLD);
if (myid != 0){
// All processors receive the same messages, and they will take only one letter of your name
//xnum = myid;
xnum = countname[myid]*myid;
cout << "xnum:" << xnum;
}
MPI_Finalize();
return 0;
谢谢!