用c语言实现循环队列,队列数组长度为10000,每输入500个点计算一次这500个点的方差,如果大于200则把这500个点全部打印出来
时间: 2024-05-05 21:20:54 浏览: 48
以下是用C语言实现循环队列的代码,其中会每输入500个点计算一次方差并判断是否大于200,如果是则打印出这500个点:
```c
#include <stdio.h>
#define MAX_SIZE 10000
// 循环队列结构体
typedef struct {
int front, rear;
int data[MAX_SIZE];
} Queue;
// 初始化队列
void initQueue(Queue *q) {
q->front = q->rear = 0;
}
// 判断队列是否为空
int isEmpty(Queue *q) {
return q->front == q->rear;
}
// 判断队列是否已满
int isFull(Queue *q) {
return (q->rear + 1) % MAX_SIZE == q->front;
}
// 入队
void enqueue(Queue *q, int value) {
if (isFull(q)) {
printf("Queue is full.\n");
return;
}
q->data[q->rear] = value;
q->rear = (q->rear + 1) % MAX_SIZE;
}
// 出队
int dequeue(Queue *q) {
if (isEmpty(q)) {
printf("Queue is empty.\n");
return -1;
}
int value = q->data[q->front];
q->front = (q->front + 1) % MAX_SIZE;
return value;
}
// 计算方差
float variance(Queue *q) {
if (isEmpty(q)) {
printf("Queue is empty.\n");
return -1;
}
int sum = 0;
float mean, variance = 0.0;
int n = q->rear - q->front;
for (int i = q->front; i < q->rear; i++) {
sum += q->data[i];
}
mean = (float)sum / n;
for (int i = q->front; i < q->rear; i++) {
variance += (q->data[i] - mean) * (q->data[i] - mean);
}
variance /= n;
return variance;
}
int main() {
Queue q;
initQueue(&q);
int value;
float var;
while (1) {
printf("Enter a value (-1 to quit): ");
scanf("%d", &value);
if (value == -1) {
break;
}
enqueue(&q, value);
if ((q.rear - q.front) % 500 == 0) {
var = variance(&q);
if (var > 200) {
printf("Variance is %.2f, printing all values:\n", var);
for (int i = q.front; i < q.rear; i++) {
printf("%d ", q.data[i]);
}
printf("\n");
}
}
}
return 0;
}
```
阅读全文