math operation not working with each iteration of for loop

I'm trying to write a for loop that will layer images from an array and decrease the opacity of the next image with each new iteration in a particular way... (opLevel = (1/(j+1))*255). However, the operation doesn't seem to be working. Printing opLevel shows zeros for each iteration when it should be 255, 128, etc. Am I missing something? (the parts of code that would draw on my image files have been commented out to avoid errors)

PImage[] img = new PImage[17];

int i;
int j;

float opLevel;

void setup() {
  size(1280, 720);

/*
  for (i=0; i < img.length; i++) {    
    img[i] = loadImage(i + ".jpg");
  }
*/

  for (j = 0; j < img.length; j++) {   

    opLevel = (1/(j+1))*255;
    tint(255, opLevel);
    //image(img[j], 0, 0);

    println(opLevel);
  }

}
Tagged:

Answers

  • Answer ✓

    The first time, j=0:

    1/(0+1) * 255 = 1/1 * 255 = 1 * 255 = 255
    

    The second time, j=1:

    1/(1+1) * 255 = 1/2 * 255 = 0 * 255 = 0
    

    "But wait!" you cry, "One divided by two does not equal zero!" Ah yes, you are right. At least, you are right when you're working with floating point numbers.

    When you're working with integers, one divided by two does equal zero!

    Try this instead:

    opLevel = (1/float(j+1))*255;
    
  • awesome thank you!!

Sign In or Register to comment.