Re: C Programming: A Modern Approach - Chapter 15 Exercise 5
- From: Steffen Buehler <steffenbuehler@xxxxxxxxxxxxxx>
- Date: Fri, 22 Jul 2005 12:54:23 +0200
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
.
- Follow-Ups:
- Re: C Programming: A Modern Approach - Chapter 15 Exercise 5
- From: Simon Morgan
- Re: C Programming: A Modern Approach - Chapter 15 Exercise 5
- References:
- C Programming: A Modern Approach - Chapter 15 Exercise 5
- From: Simon Morgan
- C Programming: A Modern Approach - Chapter 15 Exercise 5
- Prev by Date: Re: Yes/No
- Next by Date: Re: Value of k??
- Previous by thread: C Programming: A Modern Approach - Chapter 15 Exercise 5
- Next by thread: Re: C Programming: A Modern Approach - Chapter 15 Exercise 5
- Index(es):
Relevant Pages
|