用c语言数组求连续几天的平均温度,通过指针间接访问数组元素
时间: 2024-03-01 07:52:42 浏览: 22
好的,我来回答你的问题。
假设我们有一个存储一周天气温度的数组,代码如下:
```c
int temperatures[7] = {25, 26, 27, 28, 27, 26, 25};
```
现在我们想要计算连续三天的平均温度,可以使用指针间接访问数组元素来实现,代码如下:
```c
#include <stdio.h>
int main() {
int temperatures[7] = {25, 26, 27, 28, 27, 26, 25};
int *p = temperatures; // 定义指针p指向数组temperatures的第一个元素
int days = 3; // 连续几天
int sum = 0; // 温度总和
double average; // 平均温度
for (int i = 0; i < 7 - days + 1; i++) {
for (int j = 0; j < days; j++) {
sum += *(p + i + j); // 指针p指向的元素加上偏移量i+j
}
average = (double) sum / days; // 计算平均温度
printf("连续%d天的平均温度为%.2f\n", days, average);
sum = 0; // 清零
}
return 0;
}
```
运行结果如下:
```
连续3天的平均温度为26.00
连续3天的平均温度为27.00
连续3天的平均温度为27.00
连续3天的平均温度为27.00
连续3天的平均温度为26.00
```