Why does this integer division yield 0?

前端 未结 4 1127
爱一瞬间的悲伤
爱一瞬间的悲伤 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条回答
  • 2021-01-19 15:12

    You are performing integer math.

    Math between two integers will produce an integer. And the result will be rounded towards zero.

    This line:

    totalLengthSecs / totalFrames;
    

    Is likely producing a result that's between 0 and 1. And getting rounded to 0

    0 讨论(0)
  • 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

    0 讨论(0)
  • 2021-01-19 15:31

    In short: Integer division truncates

    You need the following:

    double timeLapseInterval = (double) totalLengthSecs / (double)totalFrames;
    printf("\ntimeLapseInterval : %f \n", timeLapseInterval);
    
    0 讨论(0)
  • 2021-01-19 15:31

    You are printing integers and therefore it will round down the value.

    timeLapseInterval / totalFrames will be (1 / frameRate) which will be < 1 unless frameRate is 1 (or 0 in which case you have an error dividing by 0)

    0 讨论(0)
提交回复
热议问题