Division operation is giving me the wrong result

2019-02-28 04:39发布

问题:

I'm trying to divide one number by another in Processing, and I keep getting the wrong answer.

float a;
a = 3/2;
println(a);

gives me

1.0

when then answer should be 1.5.

Trying a different number,

float a;
a = 2/3;
println(a);

gives me

0.0

when the answer should be 0.666666....

Is there something I'm missing? I looked over the Processing documentation for division and it seems like I'm using the right syntax.

回答1:

Like others have said, you're using integer division.

Remember that int values can't hold decimal places. So if you do a calculation that would result in decimal places, those values are truncated and you're left with only the whole number part (in other words, the integer part).

int x = 1;
int y = 2;
int z = x/y; //0

int x = 5;
int y = 2;
int z = x/y; //2

You're using int literal values (digits like 2 and 3), and those don't have decimal places, so Processing treats them like int values, and they obey the above rules.

If you care about the decimal places, then either store them in float or double variables:

float x = 1;
float y = 2;
float z = x/y; //.5

float x = 5;
float y = 2;
float z = x/y; //2.5

Or just use float literals by adding a decimal part:

float a = 2.0/3.0;

Processing now knows that these are float values, so you'll keep the decimal places.



回答2:

Perhaps Processing is interpreting both 3 and 2 as integers. And, since you are dividing one integer by another, it is giving you integer division.

Try changing one or both to 3.0 and/or 2.0 instead.



回答3:

Your division in interpreted as an integer division and will most probably follow Java integer division rules (since Processing seem to be based on Java).

Java inherits most of its division rules from C, these being explained in more details in a specific question/answer here.