Search code examples
cmathdivisioninteger-division

Why does 5/7 print 0?


I just started learning C, and I learnt that the / sign is the division operator. I was experimenting, and was wondering why 5/7 printf the number 0.

Here is my program:

#include<stdio.h>

main()
{
    int n;
    n = 5/7;
    printf("%d", n);
}

Thank you!


Solution

  • This is because of integer division. 5/7 makes 0.71.., and the integer part of this number is 0, hence it prints 0. To solve this problem use float type (or double type) variables as well as constants for example try:

    float f = 5.0 / 7.0;
    

    print variable f with format string %f