Division operation is giving me the wrong result

前端 未结 3 1867
死守一世寂寞
死守一世寂寞 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.

提交回复
热议问题