好的,这不行! 这有什么问题。 有人可以向我指出。我盯着它好几个小时。 我之前已经寻求过帮助,他提出了结构但我没有真正得到它而且它不起作用。
没有得到正确的计算。我认为阅读文件可能有问题。 / * 读取二进制文件并计算多边形的参数 * /
typedef int16_t points[2];
int main(int argc, char* argv[]) {
FILE* fp = fopen(argv[1], "rb");
// int points[1000];
//long numbytesread=0;
int16_t num_of_coors=0;
//open the files
if( fp == NULL ) {
printf("Could not open.\n");
return -1; // -1 indicates error
}
//read file
fread(&num_of_coors, sizeof(int16_t), 2, fp);
points*points=malloc(sizeof(points)*num_of_coors);
fread(points, sizeof(points), num_of_coors, fp);
//read the array and seperate x coordinates and y coordinates
//calculate using formula (x1-x2)^2+(y1-y2)^2
//need 2 points, 4 coordinates at any single time. read a pair at a time
double sum=0;
int i=0;
//int coors=points[0]*2+1 ;
for(i=1;i<=num_of_coors;i++){
sum+=sqrt(pow((points[i]-points[i+2]),2) + pow((points[i+1]-points[i+3]),2));
}
sum+=sqrt(pow((points[1]-points[num_of_coors-2]),2) + pow((points[2]-points[num_of_coors-1]),2));
printf("The perimeter is %.2lf\n", sum);
fclose(fp);
free(points);
}
答案 0 :(得分:0)
我猜你文件的二进制格式是:
int16_t <num of points>
int16_t <Xcoord> int16_t <Ycoord>
....
首先,对于类型名称和变量名称使用相同的名称是不好的方法。 其次,你使用'点'类型是不正确的。 正确的代码应如下所示:
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
/*
read binary file and calculate parameter of polygon
*/
typedef int16_t points[2];
int main(int argc, char* argv[]) {
FILE* fp = fopen(argv[1], "rb");
// int points[1000];
//long numbytesread=0;
int16_t num_of_coors=0;
//open the files
if( fp == NULL ) {
printf("Could not open.\n");
return -1; // -1 indicates error
}
//read file
fread(&num_of_coors, sizeof(int16_t), 1, fp);
points* p=malloc(sizeof(points)*num_of_coors);
fread(p, sizeof(points), num_of_coors, fp);
//read the array and seperate x coordinates and y coordinates
//calculate using formula (x1-x2)^2+(y1-y2)^2
//need 2 points, 4 coordinates at any single time. read a pair at a time
double sum=0;
int i=0;
//int coors=points[0]*2+1 ;
for(i=1;i<num_of_coors;i++) {
sum+=sqrt(pow(p[i-1][0]-p[i][0],2)+pow(p[i-1][1]-p[i][1],2));
}
sum+=sqrt(pow(p[0][0]-p[num_of_coors-1][0],2)+pow(p[0][1]-p[num_of_coors-1][1],2));
printf("The perimeter is %.2lf\n", sum);
fclose(fp);
free(p);
return 0;
}