Originally Posted by
nine-hundred
I think a lot of my problem may lie in that this fraction wouldn't always be coming out to a whole number and you can print say .3 of a space...
Suppose you need to print 4.5 spaces between each word. That's 9 spaces between every two words. So if you alternate between 4 and 5 spaces, every other word, you insert, on average, 4.5 spaces per word.
You can generalize this in the following way:
Code:
double total_error = 0.0;
double nspace = (m - c) / (w - 1); /* Ideal number of spaces per word (not an integer) */
double space_error = nspace - floor(nspace); /* Fractional part of nspace */
for(each word)
{
if(total_error >= 1.0)
{
/* Error exceeds a space, so subtract a full unit of error and generate an extra
* space */
output_spaces(1);
total_error -= 1.0;
}
output(word);
output_spaces(floor(nspace));
total_error += space_error;
}
Where output_spaces() is a function that outputs the given number of spaces.
This is closely related to a few other algorithms, like Bresenham line drawing, or box-filter image scaling.
Also, it can be implemented entirely with integer math, but that's a trick I keep to myself.