K&R answer book exercise 1.21

前端 未结 2 841
广开言路
广开言路 2021-01-24 01:08

Here is the question:

Write the program entab that replaces strings of blanks by the minimum number of tabs and blanks to achieve the same spacing. Use th

2条回答
  •  天涯浪人
    2021-01-24 01:38

    There is no specific name to this formula - it is a relatively straightforward way of applying math from the elementary school to everyday problems. Here is what's going on: '\t' character advances the pos by a number of positions ranging from one to TABINC, inclusive.

    • When pos is a multiple of TABINC, you jump the full TABINC
    • When pos is one below the next multiple of TABINC, you jump by one,
    • When pos is two below the next multiple of TABINC, you jump by two,
    • and so on - when pos is x, where 0 < x < TABINC, below the next multiple of TABINC, you jump x

    Now the problem of calculating a jump is reduced to computing the difference between pos and the next multiple of TABINC. This can be done by computing a division remainder of the pos and TABINC, and subtracting that remainder from the TABINC. This is done with the % operator.

    Since pos is one-based *, the first thing the formula does is making it zero-based for the purpose of calculating the remainder. Next, the formula computes the remainder, which is a mathematical way of saying "the number of positions above the last TABINC stop". Now all you need is subtracting that remainder from TABINC to get your result.

    * The assignment pos=0 on discovering '\n' seemingly contradicts the assertion that pos is one-based. However, the loop header performs pos++ after each iteration, so the next iteration of the loop sees pos=1 on the next iteration.

提交回复
热议问题