Multiplication of two int's gets negative

后端 未结 4 1399
隐瞒了意图╮
隐瞒了意图╮ 2021-01-22 11:26

I\'m currently coding a little download manager and I get a funny output when I try to calculate the download-progress in percent. This is what i use to calculate it:

         


        
相关标签:
4条回答
  • 2021-01-22 12:14
    2^31-1 = 2147483647  < 21476160 * 100 = 2147616000
    
    0 讨论(0)
  • 2021-01-22 12:18

    See http://en.wikipedia.org/wiki/Arithmetic_overflow

    To fix in java, try using a long instead.

    int progress = (int) ((byte_counter * 100L) / size);
    

    or reverse order of operations

    int progress = (int) (((float) byte_counter) / size) * 100);
    
    0 讨论(0)
  • 2021-01-22 12:22

    21476160 * 100 = 2 147 616 000 is greater than 2 147 483 647, the max int.

    You're overflowing.

    Use long for your calculations.

    0 讨论(0)
  • 2021-01-22 12:27

    You should use a long -- 2147760000 in binary is 10000000 00000100 00110111 10000000 and since the most significant bit is 1 it is interpreted as a negative number.

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