2

My file called "a.txt" contains a number (47).

If I run the program on a compiler without MPI using fscanf(a,"%f",&num) it gives a true value nnum = 47.

If I run the program using MPI ssh it does not return the correct value. it will return num = 1104187136 instead.

Why is this?

int main(int argc, char *argv[]){
  int count;
  FILE *a1;
  float a;
  int num;

  a1 = fopen("a1.txt","r");


  MPI_Init(&argc, &argv);
  MPI_Comm_size(MPI_COMM_WORLD,&numOfProc);
  MPI_Comm_rank(MPI_COMM_WORLD,&my_rank);

  if(my_rank == 0){     
    fscanf(a1,"%f",&num);
    a = num;
    printf("a = %d",a);
  }

  MPI_Finalize();
}

1 Answers1

3

I don't think the issue here is MPI, or even fscanf; the issue is the use of fscanf. If you compile with warnings on, you'll get several warnings about format codes.

To start with, you have:

int num;
fscanf(a1,"%f",&num);

which tries to read in the number as a floating point number, and then you give it a pointer to an int in which to store it. The printf/scanf format codes are a little funny; they indicate to fscanf not only how to parse the input, but what sort of representation in which to save the result. If you try copying a float representation of 47.0 into an int variable, you'll get:

int num;
float a;

a = 47.0;
*(float *)&num = a;

printf("num = %d\n", num);
...

num = 1111228416 

The same issue occurs with the printf:

a = num;
printf("a = %d",a);

Here you assign the value from num into a, which is fine, the compiler will insert the type conversion there, but then you interpret that value as an int and print it out as such, and so you get another representation/value mismatch there.

So I think in your code you want either :

fscanf(a1,"%f",&a);
printf("a = %f",a);

or

fscanf(a1,"%d",&num);
printf("num = %d",num);

but not the conversions the way you have them.

Jonathan Dursi
  • 50,107
  • 9
  • 127
  • 158