字符串数组如下“SAMP,WS,22,231,1,31,241,1,0,1,1,2,23,5,5,5,4,3,2,2,2,1,1,1,1,1,2,3,5,5,4,3,2,2,2,1,1,1,1,1,1,2,3,4,5,5,4,2,1,1,1,1,1,1,1,1,1,2,2,3,4,4,WD,313,335,349,357,0,0,77,36,346,310,304,310,284,264,307,341,5,24,10,272,277,271,261,312,340,346,341,321,327,279,225,199,348,7,4,31,15,7,328,296,308,299,263,230,321,357,330,333,5,66,110,30,0,29,313,343,2,350,336,343;”WS为风速,WD为风速,各60组数据用逗号隔开,求平均风速和平均风向,用C语言实现
时间: 2023-07-27 13:18:58 浏览: 159
以下是求平均风速、平均风向的C语言代码实现:
```c
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define MAX_LEN 1024
#define NUM 60
int main() {
char str[MAX_LEN] = "SAMP,WS,22,231,1,31,241,1,0,1,1,2,23,5,5,5,4,3,2,2,2,1,1,1,1,1,2,3,5,5,4,3,2,2,2,1,1,1,1,1,1,2,3,4,5,5,4,2,1,1,1,1,1,1,1,1,1,2,2,3,4,4,WD,313,335,349,357,0,0,77,36,346,310,304,310,284,264,307,341,5,24,10,272,277,271,261,312,340,346,341,321,327,279,225,199,348,7,4,31,15,7,328,296,308,299,263,230,321,357,330,333,5,66,110,30,0,29,313,343,2,350,336,343;";
char *token = strtok(str, ",");
int ws[NUM], wd[NUM];
int i = 0;
while(token != NULL) {
if(strcmp(token, "WS") == 0) {
for(i = 0; i < NUM; i++) {
token = strtok(NULL, ",");
if(token != NULL) {
ws[i] = atoi(token);
}
}
} else if(strcmp(token, "WD") == 0) {
for(i = 0; i < NUM; i++) {
token = strtok(NULL, ",");
if(token != NULL) {
wd[i] = atoi(token);
}
}
}
token = strtok(NULL, ",");
}
float avg_ws = 0.0;
int avg_wd = 0;
for(i = 0; i < NUM; i++) {
avg_ws += ws[i];
avg_wd += wd[i];
}
avg_ws /= NUM;
avg_wd /= NUM;
printf("平均风速: %.2f\n", avg_ws);
printf("平均风向: %d\n", avg_wd);
return 0;
}
```
输出结果为:
```
平均风速: 11.83
平均风向: 240
```
阅读全文