Chapter 6 - Question 1

A sawmill operates a robot controlled power saw to cut planks into standard-lengths. The machine can be pre-set to the number of standard-lengths to be cut and the length of a standard-length. In addition, it maintains a record of the number of standard-lengths cut, the number of planks used and the total amount of timber that was too short to produce a standard-length.

Design a program to simulate the action of the machine using numbers entered from the keyboard to represent planks. The values on the counters should be printed before the program terminates.

Solution 1

C++:

#include <stdio.h>intmain(intargc,char*argv[]){intiStandardLength,iAmount,iPlankLength,iUnused=0,iCut=0;// get the standard lengthprintf("Enter the standard-length in centimeters:\n>");scanf("%d",&iStandardLength);// get the amount to cutprintf("Enter the number of standard-lengths to cut:\n>");scanf("%d",&iAmount);// loop until enough standard lengths have been madewhile(iCut<iAmount){// get the plank size from the operatorprintf("Enter a plank into the machine and enter the length in centimeters:\n>");scanf("%d",&iPlankLength);// if it would make too manyif(iCut+(iPlankLength/iStandardLength)>iAmount){// don't slice up bits that could be used for somethingiUnused+=iPlankLength-((iAmount-iCut)*iStandardLength);// just make enoughiCut=iAmount;}// if it wouldn't make enoughelse{// make as many as possibleiCut+=iPlankLength/iStandardLength;// store the restiUnused+=iPlankLength%iStandardLength;}// show the totals so farprintf("%d total standard-lengths cut. %dcm total unused timber.\n",iCut,iUnused);}return0;}

Here's an example run through the program:

C:\code>sawmill
Enter the standard-length in centimeters:
>5
Enter the number of standard-lengths to cut:
>7
Enter a plank into the machine and enter the length in centimeters:
>13
2 total standard-lengths cut. 3cm total unused timber.
Enter a plank into the machine and enter the length in centimeters:
>4
2 total standard-lengths cut. 7cm total unused timber.
Enter a plank into the machine and enter the length in centimeters:
>15
5 total standard-lengths cut. 7cm total unused timber.
Enter a plank into the machine and enter the length in centimeters:
>23
7 total standard-lengths cut. 20cm total unused timber.