【发布时间】:2015-06-29 17:35:24
【问题描述】:
尝试使用重定向从 .txt 文件中计算取 (x,y) 坐标最多 100 个点的多边形面积,例如./program
我在扫描输入时遇到问题,因此我的函数将计算面积。
输入是:
3 12867 1.0 2.0 1.0 5.0 4.0 5.0
其中 3 是 npoints,12867 是标识号。
这是我到目前为止生成的代码:
#include <stdio.h>
#include <stdlib.h>
#define MAX_PTS 100
#define MAX_POLYS 100
#define END_INPUT 0
// function to calculate the area of a polygon
// think it's correct
double polygon_area(int MAX_PTS, double x[], double y[])
{
printf("In polygon.area\n");
double area = 0.0;
for (int i = 0; i < MAX_PTS; ++i)
{
int j = (i + 1)%MAX_PTS;
area += 0.5 * (x[i]*y[j] - x[j]*y[i]);
}
printf("The area of the polygon is %lf \n", area);
return (area);
}
// having trouble reading in values from a txt file into an array
int main(int argc, char *argv[]) {
int npoints, poly_id;
double // something should go here
if(scanf("%d %d", &npoints, &poly_id)) {
int iteration = 0;
struct Point initialPoint = a;
double area = 0;
scanf("%lf %lf", &, &);
// keep getting errors with what goes next to the &
for (iteration = 1; iteration < npoints; ++iteration) {
scanf("%lf %lf", &, &);
// keep getting errors with what goes next to the &
area += polygon_area(); // unsure what to do here
}
// now complete the polygon with last-edge joining the last-point
// with initial-point.
area += polygon_area(a, initialPoint);
printf("First polygon is %d\n", poly_id);
printf("area = %2.2lf m^2\n", area);
}
return 0;
}
我碰巧是编码新手,所以过去使用数组和结构的任何东西我都不会真正理解,但仍然感谢任何帮助!
【问题讨论】:
-
请详细介绍 npoint 和标识号。它的用途是什么? (x,y) 坐标在哪里?
-
我怀疑
scanf("%lf %lf", &, &);会编译。这至少应该是&a.x, &a.y或与 Point 的定义兼容的东西。 -
您不能将
MAX_PTS用作#define 和参数名称。它不起作用,因为编译器会将您的变量名视为 100,这是一个非法的变量名。 -
"keep getting errors with what goes next to the &":嗯,这很有意义,考虑到您的代码中&旁边没有任何内容!!! -
只是一个提示,如果您没有有使用 C,请使用其他东西。例如,Python 对于这样的简单任务要容易得多。
标签: c arrays polygon scanf area