Division operation is giving me the wrong result

不问归期 提交于 2019-12-02 05:17:41

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.

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.

Alexei

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.

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!