About the division of floating point numbers in C language。

Viewed 46

I am a university student. When learning C language, I encountered the problem of floating point division. Can anyone help me to see why the results are different every time I run it. thank you very much.( I am running in a Linux)

My English is not good, hope you can understand the meaning of my question。

#include <stdio.h>
int main()
{
    double a = 1;
    double b = 2;
    printf("%d\n",b/a);
    return 0;
}
1 Answers

You're using the wrong format specifier.

The %d former specifier for printf expects an int as an argument, but you're passing in a double. Using the wrong format specifier triggers undefined behavior.

You should instead use %f which is for printing a double.

printf("%f\n",b/a);
Related