Fulvio Denza
Fulvio Denza

Reputation: 67

1.#QNANO in output in C language?

#include <stdio.h>

float diff_abs(float,float);

int main() {
  float x;
  float y;
  scanf("%f", &x);
  scanf("%f", &y);
  printf("%f\n", diff_abs(x,y));
  return 0;
}

float diff_abs(float a, float b) {
  float *pa = &a;
  float *pb = &b;
  float tmp = a;
  a = a-b;
  b = *pb-tmp;
  printf("%.2f\n", a);
  printf("%.2f\n", b);
}

Hello guys, i'm doing a C program which should keep in a variable a-b, and in b variable b-a. It's all ok, but if i run my code at the end of output, compiler shows me this message:

3.14
-2.71
5.85
-5.85
1.#QNAN0

what does means 1.#QNANO?

Upvotes: 0

Views: 3549

Answers (2)

Sourav Ghosh
Sourav Ghosh

Reputation: 134356

The problem is, you don't return a value from the called function diff_abs() and you're trying to use the return-ed value. It invokes undefined behavior.

Quoting C11, chapter §6.9.1, Function definitions

If the } that terminates a function is reached, and the value of the function call is used by the caller, the behavior is undefined.

Based on your comments, it appears, you are not needed to have any return value from the function. In that case,

  • Change the function signature to return type void
  • Just call the function, get rid of the last printf() call in main() altogether. The printf()s inside the called function will get executed and the prints will appear on their own, you don't need to pass the function as an argument to another printf() for that.

Upvotes: 1

ReshaD
ReshaD

Reputation: 946

In this piece of code printf("%f\n", diff_abs(x,y)) you are telling the compiler to print a float type of variable which should be the return value of the function diff_abs. But in your function diff_abs you are not returning any value.

So %f which is waiting for a float, will not get any value and it will print #QNAN0 which means Not A Number. So you can change your code as follows:

In your main:

//printf("%f\n", diff_abs(x,y));   //comment this line
diff_abs(x,y);  //just call the function

In the function:

void diff_abs(float a, float b) {  //change the return value to void
  //float *pa = &a;   //you are not using this variable
  float *pb = &b;
  float tmp = a;
  a = a-b;
  b = *pb-tmp;
  printf("%.2f\n", a);
  printf("%.2f\n", b);
  return;
}

Upvotes: 1

Related Questions