2016-11-17 12 views
2

私はCの初心者です(C++での経験はほとんどありません)。ユーザー入力変数の値に問題があります。私はMPI_ScatterMPI_GatherというプログラムをC言語で書いて、各ノードの入力された整数の総和を計算しました。C言語のユーザー入力変数値

問題は次のとおりです。変数入力をinput=5;と定義すると、すべての4ノード(210)の合計が計算されます。 scanfの入力を設定すると、結果は15になります。変数がその値を変更するようです。私を助けてくれますか? コード:

#include "mpi.h" 
#include <stdio.h> 
#include <stdlib.h> 
#define MASTER 0 
int main(int argc, char** argv){ 
    int id, nproc; 
    MPI_Init(&argc, &argv); 
    MPI_Comm_size(MPI_COMM_WORLD, &nproc); 
    MPI_Comm_rank(MPI_COMM_WOLRD, &id); 
    MPI_Status status; 
    int input=0; // <- problematic variable 
    int nodeValue=0; 
    int size; 
    int *array; 
    if(id == MASTER){ 
    printf("How many elements per node? "); 
    scanf("%d", &input); 
    nodeValue = input; 
    } 
    MPI_Barrier(MPI_COMM_WORLD); 
    if(id == MASTER){ 
    size = input * nproc; 
    array = malloc(sizeof(int)*size); 
    ... 
    } 
} 
+0

'scanf'の戻り値は何ですか? – Swanand

+0

標準入力から多くのスレッドを読み取っていますか? –

+0

scanfの戻り値はどうですか? @Swanand – ZPA

答えて

4

あなたのクエリは、スタックオーバーフローの問題以下のようになります。 訪問として与えIn MPI for multiple process scanf taking input only once and assign garbage values to other?

オプション:ファイルからの入力をお読みください。ここで

ファイルから読み込むためのサンプルコードです:それは本当にユーザー入力を必要とされている場合は 訪問https://docs.loni.org/wiki/c_mpi_examples

:ここ

#include "mpi.h" 
    #include <stdio.h> 
    #include <stdlib.h> 

    int main(int argc, char *argv[]) 
    { 
    int myid, nprocs; 
    int *array; 
    int size, i; 
    FILE *fp; 

    MPI_Init(&argc, &argv); 
    MPI_Comm_rank(MPI_COMM_WORLD, &myid); 
    MPI_Comm_size(MPI_COMM_WORLD, &nprocs); 

    if(myid ==0) 
    { 
    fp = fopen("test", "r"); 
    fscanf(fp, "%d", &size); 
    } 

    /* MPI_Bcast(void *buffer, 
      int count, 
      MPI_Datatype datatype, 
      int root, 
      MPI_Comm comm) */ 
    MPI_Bcast(&size,1, MPI_INT, 0, MPI_COMM_WORLD); 
    array = (int *) malloc(size* sizeof(int)); 

    if(myid ==0) 
    { 
    for(i = 0; i < size; i++) 
    { 
    fscanf(fp, "%d", &array[i]); 
    } 
    } 
    MPI_Bcast(array, size, MPI_INT, 0, MPI_COMM_WORLD); 

    MPI_Finalize(); 
    } 

はリンクになっていくつかの例を持っている私たちが持っているオプションは

です

1)コマンドライン引数またはファイルから読み込みます(長時間のアプローチですが、そのファイルに入力するコードを書きます)

2)MPI_Initの後、STDINは期待通りに動作しません。 MPI_Initの前にscanfステートメントを置こうとしてください。

修正コード:これを試してください:

int id, nproc; 
    MPI_Status status; 
    int input=0; // <- problematic variable 
    int nodeValue=0; 
    int size; 
    int *array; 
    if(id == MASTER){ 
    printf("How many elements per node? "); 
    scanf("%d", &input); 
    nodeValue = input; 
    } 
    MPI_Init(&argc, &argv); 
    MPI_Comm_size(MPI_COMM_WORLD, &nproc); 
    MPI_Comm_rank(MPI_COMM_WOLRD, &id); 
+0

申し訳ありませんが、ユーザー入力はマスター部分にある必要があります.- – ZPA

+0

ありがとう、@ハビシェリフ、しかし入力はユーザーによって行われなければなりません。とにかく助けてくれてありがとう、私はすでにあなたのリンクを以前チェックした。 – ZPA

+0

これは許可されていません。「MPICHを初期化する前にMPIルーチンを使用しようとしています。 @ハビ・シェリフ – ZPA

関連する問題