Processing is getting zero from a division

edited May 2017 in Raspberry PI

Hello! The problem I've is: When I make a division (using float) the result is always getting 0 decimals. I mean, let's say I've this:

float a = 10.25; float b = 123/12;

It should be exactly the same but, if I make a display the result would be a=10.25 (that's ok) and b = 10.0 Why processing is not capable of work with the full number? I got the same result with every division, for instance 1/10 is always 0.0

Thanks a lot!!

Tagged:

Answers

  • edited May 2017

    @v13duran --

    Why processing is not capable of work with the full number?

    It is performing integer division because you specified two integers, then divided them. 10 is the number of whole times that 12 goes into 123. Instead try:

    println( 123/12     ); // 10
    println( 123.0/12   ); // 10.25
    println( 123/12.0   ); // 10.25
    println( 123.0/12.0 ); // 10.25
    println( (float)123/12 ); // 10.25
    
  • Okey, I got it. I must write: float b = 123.0/12.0;

    Without .0 it's not going to work...

  • edited May 2017

    Writing ".0" makes a value a float, as you say. You can get a fractional division answers by making:

    1. the numerator a float (float/int)
    2. the denominator a float (int/float)
    3. both floats (float/float)

    Only int/int gives integer division answers.

    You may also be interested in this past discussion of rounding:

Sign In or Register to comment.