I have an error with divide (float issue)

I had a problem with a code, so I wrote a small one,
and when I run it,
it print 0.0, instead 0.2

What am I missing?

void setup(){
noLoop();
}

void draw(){
  float a = 2/10;
  println(a);
}
1 Like

Try 2/10.0;

Otherwise java sees it as integer
Chrisir

2 Likes

This is called integer division because both numbers, 2 and 10 are integers.

Cast you mind back to junior school when you only knew about whole numbers and the teacher asks you

What do you get when you divide seven by two?

You would reply

Three remainder one

In Integer division the remainder is ignored and only the first part is returned so
7/3 returns 2

So two divided by ten is zero remainder two hence
2/10 returns 0

NOTE: Integer division always returns an integer. In the expression
float a = 2/10;
The assignment operator (=) will take the integer 0 from the right hand side and store in a float variable on the left hand side. So when you print a you get 0.0 not 0

The solution is to change one or both of the numbers to float as shown in previous post.

5 Likes

thanks for the awesome information.

1 Like