Division operation is giving me the wrong result

前端 未结 3 1820
死守一世寂寞
死守一世寂寞 2021-01-27 01:55

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

float a;
a = 3/2;
prin         


        
相关标签:
3条回答
  • 2021-01-27 02:12

    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.

    0 讨论(0)
  • 2021-01-27 02:17

    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.

    0 讨论(0)
  • 2021-01-27 02:26

    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.

    0 讨论(0)
提交回复
热议问题