Search code examples
ctypescastingoperator-precedence

How to convert int to Double in C programming


int num1, num2;

double average;

average=(double)(num1+num2)/2;
printf("average: %d", average);

My test printf shows average as: 0

This is maybe too easy, but I can't see it. My inputs are both "int" and the average is "double" but somehow it is not calculating right ?


Solution

  • You're using the wrong format specifier to printf.

    The %d format specifier expects an int argument, but you're passing a double. Using the wrong format specifier invokes undefined behavior.

    To print a double, use %f.

    printf("average: %f\n", average);