Why does dividing a float by an integer return 0.0?

前端 未结 6 1725
不思量自难忘°
不思量自难忘° 2020-11-28 13:07

So if I have a range of numbers \'0 - 1024\' and I want to bring them into \'0 - 255\', the maths would dictate to divide the input by the maximum the input will be (1024 in

6条回答
  •  暗喜
    暗喜 (楼主)
    2020-11-28 13:38

    It's because you're doing integer division.

    Divide by a double or a float, and it will work:

    double scale = ( n / 1024.0 ) * 255 ;
    

    Or, if you want it as a float,

    float scale = ( n / 1024.0f ) * 255 ;
    

提交回复
热议问题