Width and Height are completely different values, but Width/Height is turning out 0

edited January 2017 in Questions about Code

I am utterly confused at this one and at my wit's end. I try to divide width by height, width being 958 and height being 1328, and it returns 0. It should even be rounded to 0, if anything it should round to one! Here is my code:

float size;
float biggerSize;
int x;
int y;
PImage img;
boolean horizontal;

void setup() {
    //img = loadImage("GraywolfGravatar.jpg");
    //img = loadImage("WolfGravatar2016.jpg");
    size(958,1328);
    //surface.setSize (img.width, img.height);
    if (width >= height) {
        horizontal = true;
    } else {
        horizontal = false;
    }
    background (255);
    noStroke();
    noSmooth();
    frameRate(2);
    x = 0;
    y = 0;
    size = 16;
    if (horizontal) {
        biggerSize = width/height * size;
    } else {
        biggerSize = height/width * size;
    }
    println(width);
    println(height);
    println(width/height);
    println(biggerSize);
    println(size);
}

void draw() {
    //image(img, 0, 0);
    fill(255,0,0);
    triangle(x*width/size,y*height/biggerSize, (x+1)*width/size,(y+1)*height/biggerSize, (x+1)*width/size,y*height/biggerSize);
    fill(0,0,255);
    triangle(x*width/size,y*height/biggerSize, (x+1)*width/size,(y+1)*height/biggerSize, x*width/size,(y+1)*height/biggerSize);

    if (horizontal) {
        if (x < biggerSize - 1) {
            println(x);
            x++;
        } else if (y < size - 1) {
            y++;
            x = 0;
        }
    } else {
        if (x < size - 1) {
            x++;
        } else if (y < biggerSize - 1) {
            y++;
            x = 0;
        }
    }
}

void mouseClicked() {
    setup();
}

void keyPressed() {
    if (key == CODED) {
        if (keyCode == UP) {
            int[] imageSaveCount = int(loadStrings("data/imageSaveCount.txt"));
            saveFrame("images/artwork-" + (imageSaveCount[0] + 1) + ".png");
            saveStrings("data/imageSaveCount.txt", new String[] {"" + (int(imageSaveCount[0]) + 1)});
        }
    }
}

Any help or explanation you can provide would be great. Thanks!

Tagged:

Answers

  • edited January 2017 Answer ✓

    In Java when both operands of the division operator are of whole type the fractional part is eliminated!

    How about store width & height as float datatype, so you can divide them w/o any fear? *-:)

    static final int SIZE = 16;
    
    boolean horizontal;
    float w, h, biggerSize;
    
    void setup() {
      //size(600, 400);
      size(400, 600);
    
      w = width;
      h = height;
      horizontal = w >= h;
      biggerSize = SIZE * (horizontal? w/h : h/w);
    
      println(w, h, horizontal, biggerSize);
      exit();
    }
    
  • @GoToLoop Thanks, I couldn't have asked for a better answer!

Sign In or Register to comment.