# 計數器實作

## 自動計數器

要建立一個計數器，最核心的地方就是要使用一個變數來記錄目前的數字，同時還要有一個變數用來決定現在是要正數還是倒數。第一個變數我們以「counter」來命令，另外一個變數則把它叫做「delta」。此時變數積木中，會有3個變數，其中那個index是原先就是預設。

![](/files/-LNgkhee4UQOk36iW_mI)

在啟動的時候，如上所想，要把這兩個變數分別設定其初始值為0以及1：

![](/files/-LNgkyxGd2X8tr6ftIfi)

由於需要歸零的功能，我們就設定「A+B」按鈕被按下的時候，把counter設定為零，如下：

![](/files/-LNglJ8nZcU-YS7dREa5)

如果A被按下就正數，也就是delta設定為1，而B被按下時則倒數，也就是delta要設定為-1，如下所示：

![](/files/-LNgldsuz6MtUohAvb1C)

最後，控制在重複無限次的地方每隔1秒就顯示出目前的counter，同時顯示完成之後，就把counter的值加上delta，如果這時候delta是1就是正數，-1就是倒數。

![](/files/-LNgmFG54i0a4KaW6Qe6)

如果，你想要限制計數的過程中不能讓數字變成負數的話，則可加上如下所示的限制：

![](/files/-LNgmgtLN88EcTFqsNek)

如此，如果在倒數的情況下，就永遠不會數到負數，最會一直停留在0，直到我們改為正數為止。

## 手動計數器

前一個例子是在固定的時間中自動計數，那如果想要做的是手動的計數器，按A按鈕加1，按B按鈕減1，A+B一起按的時候則是歸零，該如何做呢？

首先，在重複無限次的地方，把它變成很單純地顯示counter這個變數就可以了，如下所示：

![](/files/-LNgnpnULief6-eUycbS)

然後A按鈕被按下以及B按鈕被按下的事件，則是真正執行加1及減1的操作，當然A+B按鈕的事件也是把counter設為0，而啟動時要做的就只有將counter設為0的動作，在這個例子中，delta變數是沒有作用的：

![](/files/-LNgoT4q6VbVphvAqeom)


---

# Agent Instructions: Querying This Documentation

If you need additional information that is not directly available in this page, you can query the documentation dynamically by asking a question.

Perform an HTTP GET request on the current page URL with the `ask` query parameter:

```
GET https://nkust.gitbook.io/micro-bit/qi-zuo.md?ask=<question>
```

The question should be specific, self-contained, and written in natural language.
The response will contain a direct answer to the question and relevant excerpts and sources from the documentation.

Use this mechanism when the answer is not explicitly present in the current page, you need clarification or additional context, or you want to retrieve related documentation sections.
