Re: C Programming: A Modern Approach - Chapter 15 Exercise 5



Simon Morgan wrote:

> The following code pads out sentences with extra spaces between words
> so that each line takes up the same amount of space on screen. As is,
> the code will favour the end of the line when distributing the extra
> spaces. The task is to modify it so that it alternates between
> distribution of the extra spaces favouring the end of the line and
> the beginning of the line.
>
> void write_line(void)
> {
> int extra_spaces, spaces_to_insert, i, j;
>
> extra_spaces = MAX_LINE_LEN - line_len;
> for (i = 0; i < line_len; i++) {
> if (line[i] != ' ')
> putchar(line[i]);
> else {
> spaces_to_insert = extra_spaces / (num_words - 1);

This is the troublemaker. Let's say you have 8 extra spaces and 4 words.
Then spaces_to_insert will be 8/3 = 2.666 and be _cut_ _off_ to 2. So
"too few" spaces will be inserted first.

If you want to have "too much" spaces first, change this line to

spaces_to_insert = int(0.5 + extra_spaces / (num_words - 1.0);

(Beware to make the division floating-point by using 1.0 instead of 1 or
casting extra_spaces to float, otherwise the rounding will not work.)

> for (j = 1; j <= spaces_to_insert + 1; j++)
> putchar(' ');
> extra_spaces -= spaces_to_insert;
> num_words--;
> }
> }
> putchar('\n');
> }

Regards
Steffen

.



Relevant Pages

  • C Programming: A Modern Approach - Chapter 15 Exercise 5
    ... The following code pads out sentences with extra spaces between words so ... code will favour the end of the line when distributing the extra spaces. ... extra spaces favouring the end of the line and the beginning of the line. ...
    (comp.lang.c)
  • Re: C Programming: A Modern Approach - Chapter 15 Exercise 5
    ... > code will favour the end of the line when distributing the extra spaces. ... > extra spaces favouring the end of the line and the beginning of the line. ... extra space at each of the N%S gaps at the ...
    (comp.lang.c)