【发布时间】:2015-07-01 03:39:08
【问题描述】:
下面是我的程序,它在给定一定数量的 (x,y) 坐标的情况下确定多边形的周长和面积,但我似乎得到了错误的输出,我不明白为什么。
输入是:
3 12867 1.0 2.0 1.0 5.0 4.0 5.0
5 15643 1.0 2.0 4.0 5.0 7.8 3.5 5.0 0.4 1.0 0.4
第一个条目是点(点)的数量,第二个条目是多边形 ID,之后的任何内容都是一组坐标。
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
#define MAX_PTS 100
#define MAX_POLYS 100
#define END_INPUT 0
struct Point {
double x, y;
};
double getDistance(struct Point a, struct Point b) {
double distance;
distance = sqrt((a.x - b.x) * (a.x - b.x) + (a.y-b.y) *(a.y-b.y));
return distance;
}
double polygon_area(int length, double x[], double y[]) {
double area = 0.0;
for (int i = 0; i < length; ++i) {
int j = (i + 1) % length;
area += (x[i] * y[j] - x[j] * y[i]);
}
area = area / 2;
area = (area > 0 ? area : -1 * area);
return (area);
}
int main(int argc, char *argv[]) {
int npoints, poly_id;
struct Point a, b;
if(scanf("%d %d", &npoints, &poly_id)) {
int iteration = 0;
scanf("%lf %lf", &a.x, &a.y);
struct Point initialPoint = a;
double perimeter = 0; // i start with 0 value of parameter.
for (iteration = 1; iteration < npoints; ++iteration) {
scanf("%lf %lf", &b.x, &b.y); // take input for new-point.
perimeter += getDistance(a, b); // add the perimeter.
// for next iteration, new-point would be first-point in getDistance
a = b;
}
// now complete the polygon with last-edge joining the last-point
// with initial-point.
perimeter += getDistance(a, initialPoint);
printf("First polygon is %d\n", poly_id);
printf("perimeter = %2.2lf m\n", perimeter);
scanf("%d %d", &npoints, &poly_id);
double x[MAX_PTS], y[MAX_PTS];
double area = 0;
for (iteration = 0; iteration < npoints; ++iteration) {
scanf("%lf %lf", &(x[iteration]), &(y[iteration]));
}
area = polygon_area(npoints, x, y);
printf("First polygon is %d\n", poly_id);
printf("area = %2.2lf m^2\n", area);
} else if(scanf("%d", &npoints)==0) {
exit(EXIT_SUCCESS);
}
return 0;
}
我不断得到的输出是:
First polygon is 12867
perimeter = 10.24 m
First polygon is 15643
area = 19.59 m^2
但我想要的输出是:
First polygon is 12867
perimeter = 10.24 m
First polygon is 12867
area = 4.50 m^2
或者:
First polygon is 12867
perimeter = 10.24 m
area = 4.50 m^2
如果有人能指出我哪里出错了,将不胜感激。
【问题讨论】:
-
我建议学习如何使用调试器。这个想法是逐行检查你的代码并检查变量,直到你发现错误。另一种方法是在战略点使用
printf输出值。 -
在计算第一个多边形的面积之前,您正在读取第二个多边形。将第一个多边形的坐标读入一个数组,这样您就可以计算周长和面积。
-
你的问题标题说输出有问题,但实际上并不是问题。问题显然出在代码上,而不是输出问题。当有人阅读问题标题时,这不是他们所期望的问题。
-
这是垃圾输入/垃圾输出代码或数据问题。如果您确定您的第一个多边形区域在其 3 个点的情况下是正确的,那么它似乎指向 5 点多边形的数据不好。我不知道您对代码有什么期望,但它似乎在
polygon_area中没有任何明显的语法类型错误。您可以再次检查您的计算——也许在 3 点测试中未使用或最小化的一个方面确实存在逻辑问题,在进行 5 点计算之前不是问题。仔细检查数据和计算。
标签: c arrays loops struct polygons