Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
239 views
in Technique[技术] by (71.8m points)

java - Why does dividing a float by an integer return 0.0?

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 this case) which will give me a number between 0.0 - 1.0. then multiply that by the destination range, (255).

Which is what I want to do!

But for some reason in Java (using Processing) It will always return a value of 0.

The code would be as simple as this

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

But I just get 0.0. I've tried double and int. all to no avail. WHY!?

question from:https://stackoverflow.com/questions/3779604/why-does-dividing-a-float-by-an-integer-return-0-0

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Reply

0 votes
by (71.8m points)

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 ;

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
OGeek|极客中国-欢迎来到极客的世界,一个免费开放的程序员编程交流平台!开放,进步,分享!让技术改变生活,让极客改变未来! Welcome to OGeek Q&A Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...