Why does this integer division yield 0?

前端 未结 4 1166
爱一瞬间的悲伤
爱一瞬间的悲伤 2021-01-19 14:53

Could someone tell me why the following code is outputting 0 at the marked line?

It seems as if everything is correct but then when I try to get the re

4条回答
  •  猫巷女王i
    2021-01-19 15:13

    When you divide 2 numbers in C and the denominator is integer, the compiler intends it as an integer division. Therefore, if you divide 1 divided 2, it returns zero and not 0.5

    Moreover, your output variable is an integer too, hence, if you expect decimal outputs, you won't get it.

    You can fix it by doing:

    float timeLapseInterval = totalLengthSecs / (float)totalFrames;

    printf("\n\n%f", timeLapseInterval);

    I hope this helps

提交回复
热议问题