Loading…
Everything will be ready in few seconds
- Theory
- Theory
- Comments
How much does printing cost?
Back to the printer. We wrote a program that knows how to print pages, but we missed one detail: ink is used to print each page. Our printer uses 70 mg of ink per page. It would be nice to monitor the toner consumption and know how much it costs to print one document.
To solve this task, we’ll use the accumulation of values in the loop. We’ll set up an external variable, where we’ll add 70 mg (consumption per page) when printing each page of the document. But first you need to name this variable.
You do not have to invent complex names for variables, their purpose should be made clear by the name. Therefore, we determine what should be stored in the variable, for example, total ink consumption for all pages, and then translate it into English. We could call the variable consumptionColorForAllPages
or consumptionTonerForAllPages
, but this is redundant. We only solve the toner consumption task, we do not have another code, and that is why we can shorten the name and remove the indication of what we consider consumption. This is already clear, since we have no other task. A ForAllPages
too long. If we ignore the details, we calculate the total ink consumption. The English word “total” describes our purpose pretty well, and that is why we can call the variable consumptionTotal
. This name is concise and at the same time it explains the value of the variable.
Let’s repeat the procedure for the name of the variable that will store ink consumption per page (70 mg). Let’s call it consumptionPerPage
.
Let’s count toner consumption for printing all pages. We’ll make our calculations in print mode for regular documents.
- script.js
Thanks! We’ll fix everything at once!
The code has changed, click “Run” or turn autorun on.
Result
- After the variable
totalPages
, declare a variableconsumptionTotal
equal to0
. - After it, create a variable
consumptionPerPage
. It equals70
. - Inside the loop, after initiating the
muffin.print()
command, increase the value ofconsumptionTotal
variable byconsumptionPerPage
with the help of the+=
operator. - Below, in the loop, log the
consumptionTotal
value in the console.
Comments