简体   繁体   中英

evenly spaced tick markers

I have to draw tick markers at 10 percent intervals starting at zero and going to 100 percent of the width of a graphical object.

I would do something like:

int width = 556;
int k = width/10;
for(int i = 0;i<width;i++){
    if(i%k==0){
        draw marker on gui indicating a ten percent increment (10,20,etc. up to 100%)
    }
}

The problem, as you can see, is that 100% will be marked at index 550, which is 6 indices before the actual end. This is, of course, unacceptable.

Also, of course, the actual numerical value of the width is a variable that will change.

Can anyone show me how to alter the code above so that it evenly spaces the markers and also places the 100% marker at the end?

If I simply delete the tenth marker and manually place a marker at 100%, the spaces between the markers will not be even. There must be a better way of doing this, so I am hoping someone can show me.

Use doubles for decimal places. Don't go through all the mod operations. Do a simple loop of 10 iterations, one for each marker:

    int width = 556;
    double dist = ((double)width)/9.0;
    double k = 0;
    for(int i = 0; i < 10; i++){
        // Draw marker at (int)k
        k += dist;
    }

Thank you to everyone who offered suggestions. The solution I ended up using was something I came up with myself, which was to control the dimensions of the rectangle so that the width and height are integer multiples of the tick mark spacings. That way, I do not have to shuffle remainders around. Instead, I have the buffer space around the rectangle take up whatever the remainder might be with each resizing of the frame. Since the rectangle dimensions themselves are always integer multiples of the tick mark spacing, there is no longer any problem with odd-looking spacings of tick marks.

Thanks again to everyone. I just added extra +1 points to each person who tried to help.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM