c语言用队列输出斐波那锲数列的前20项
时间: 2024-03-09 20:45:31 浏览: 23
好的,这是C语言使用队列输出斐波那契数列前20项的代码:
```c
#include <stdio.h>
#define MAX_SIZE 20
// 队列结构体
struct Queue {
int data[MAX_SIZE];
int front; // 队头指针
int rear; // 队尾指针
};
// 初始化队列
void initQueue(struct Queue *q) {
q->front = 0;
q->rear = 0;
}
// 判断队列是否为空
int isEmpty(struct Queue q) {
return q.front == q.rear;
}
// 判断队列是否已满
int isFull(struct Queue q) {
return (q.rear + 1) % MAX_SIZE == q.front;
}
// 入队操作
void enqueue(struct Queue *q, int x) {
if (isFull(*q)) {
printf("Queue is full.\n");
return;
}
q->data[q->rear] = x;
q->rear = (q->rear + 1) % MAX_SIZE;
}
// 出队操作
int dequeue(struct Queue *q) {
if (isEmpty(*q)) {
printf("Queue is empty.\n");
return -1;
}
int x = q->data[q->front];
q->front = (q->front + 1) % MAX_SIZE;
return x;
}
int main() {
struct Queue q;
initQueue(&q);
int a = 0, b = 1;
enqueue(&q, a);
enqueue(&q, b);
for (int i = 0; i < MAX_SIZE; i++) {
a = dequeue(&q);
b = dequeue(&q);
printf("%d ", a);
printf("%d ", b);
enqueue(&q, b);
enqueue(&q, a + b);
}
return 0;
}
```
代码解释:
1. 定义了一个结构体 `Queue` 表示队列,包含一个数组 `data` 和两个指针 `front` 和 `rear` 分别表示队头和队尾。
2. 定义了初始化队列、判断队列是否为空、判断队列是否已满、入队操作、出队操作等函数。
3. 在 `main` 函数中,首先初始化队列,并将斐波那契数列的前两项(0和1)入队。
4. 使用循环来不断出队并输出队列中的数,同时计算下一项斐波那契数列的值,并将其入队。
5. 最后输出结果。
注意:本代码中的斐波那契数列包含了每个数的前后两项,因此输出了前20项,实际上计算了前40项。如果只需要前20项,可以修改循环条件为 `i < MAX_SIZE / 2`。
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20210720083512.png)
![rar](https://img-home.csdnimg.cn/images/20210720083606.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)