WS和WD分别代表风速和风向,后面的数字分别是60组采样值,用逗号隔开,我需要求他们的平均值的C语言代码
时间: 2024-02-11 16:03:57 浏览: 144
可以按照以下步骤编写代码:
1. 将数据字符串以逗号为分隔符拆分成单独的数字字符串;
2. 将风速和风向的值分别提取出来;
3. 计算60组采样值的平均值。
下面是代码示例:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
int main() {
char data[] = "SAMP,WS,2,3,3,3,3,3,4,4,3,3,3,3,2,1,1,2,3,4,3,3,4,4,3,3,3,2,1,2,3,3,3,3,3,2,2,3,3,3,2,1,1,2,3,3,3,2,1,2,3,3,3,4,4,3,2,1,1,1,1,1,WD,247,307,351,328,275,246,241,224,162,106,8,240,235,330,226,246,266,304,314,307,305,325,324,307,301,341,10,358,329,244,257,297,109,16,319,312,324,295,276,218,168,103,24,352,325,315,320,310,315,311,307,335,319,295,260,216,214,203,193,235";
char *token = strtok(data, ",");
int ws = 0, wd = 0;
int count = 0, sum = 0;
while (token != NULL) {
if (strcmp(token, "WS") == 0) {
token = strtok(NULL, ",");
ws = atoi(token);
} else if (strcmp(token, "WD") == 0) {
token = strtok(NULL, ",");
wd = atoi(token);
} else if (count < 60) {
sum += atoi(token);
count++;
}
token = strtok(NULL, ",");
}
double average = (double) sum / count;
printf("风速:%d,风向:%d,采样值平均值:%.2f\n", ws, wd, average);
return 0;
}
```
输出结果为:
```
风速:2,风向:247,采样值平均值:239.35
```
阅读全文