用c语言基于txt格式文件的dem数据实现填方挖方算法
时间: 2023-12-17 16:05:14 浏览: 30
下面是一个基于txt格式DEM数据实现填方挖方算法的示例代码,代码中假设DEM数据文件中存储的是地面高程数据,数据格式如下:
```
ncols 100
nrows 50
xllcorner 0.0
yllcorner 0.0
cellsize 1.0
NODATA_value -9999
10.5 11.2 9.8 ... // 第一行数据
9.6 10.2 8.9 ... // 第二行数据
... // 其他行数据
```
代码中通过读取DEM数据文件中的数据,计算出挖方体积和填方体积,并输出总体积。
```
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#define FILENAME "dem.txt"
int main()
{
float dig_height, fill_height, area, dig_volume, fill_volume, total_volume;
float **ground_height, last_height;
int count = 0, ncols, nrows;
FILE *fp = fopen(FILENAME, "r");
if (fp == NULL) {
printf("打开文件失败!\n");
return -1;
}
// 读取DEM数据文件头信息
char buf[256];
while (fgets(buf, 256, fp) != NULL) {
if (strncmp(buf, "ncols", 5) == 0) {
sscanf(buf, "ncols %d", &ncols);
} else if (strncmp(buf, "nrows", 5) == 0) {
sscanf(buf, "nrows %d", &nrows);
} else if (strncmp(buf, "cellsize", 8) == 0) {
float cellsize;
sscanf(buf, "cellsize %f", &cellsize);
} else if (strncmp(buf, "NODATA_value", 12) == 0) {
int nodata_value;
sscanf(buf, "NODATA_value %d", &nodata_value);
} else if (strncmp(buf, "xllcorner", 9) == 0) {
float xllcorner;
sscanf(buf, "xllcorner %f", &xllcorner);
} else if (strncmp(buf, "yllcorner", 9) == 0) {
float yllcorner;
sscanf(buf, "yllcorner %f", &yllcorner);
} else {
break;
}
}
// 为地面高程数组分配内存
ground_height = (float **) malloc(nrows * sizeof(float *));
for (int i = 0; i < nrows; i++) {
ground_height[i] = (float *) malloc(ncols * sizeof(float));
}
// 读取DEM数据文件中的地面高程数据
for (int i = 0; i < nrows; i++) {
for (int j = 0; j < ncols; j++) {
fscanf(fp, "%f", &ground_height[i][j]);
}
}
fclose(fp);
// 计算挖方和填方体积
for (int i = 0; i < nrows; i++) {
for (int j = 0; j < ncols; j++) {
float height = ground_height[i][j];
if (count == 0) {
last_height = height;
} else {
// 计算挖方和填方体积
if (height < last_height) {
dig_height = height;
area = 1; // 假设每个点的面积为1平方米
dig_volume += (last_height - dig_height) * area;
} else {
fill_height = height;
area = 1; // 假设每个点的面积为1平方米
fill_volume += (fill_height - last_height) * area;
}
last_height = height;
}
count++;
}
}
// 计算总体积
total_volume = dig_volume + fill_volume;
printf("总体积为:%.2f 立方米\n", total_volume);
// 释放内存
for (int i = 0; i < nrows; i++) {
free(ground_height[i]);
}
free(ground_height);
return 0;
}
```
需要注意的是,以上代码中没有对文件读取和计算错误进行处理,实际使用时需要进行相关处理。同时,也可以根据实际情况对代码进行优化和改进。