Why does dividing a float by an integer return 0.0?

前端 未结 6 1717
不思量自难忘°
不思量自难忘° 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:37

    In your case n/1024 results in 0 as you are doing integer division. To overcome this you can cast n to float. This will give you a result between 0.0 and 1.0 next you multiply with 255 and cast the result back to integer. Also you need to declare scale as int

    int scale;
    int n = 80; 
    scale = (int)(((float)n/1024) * 255);
    

提交回复
热议问题