我正在使用Malloc存储用户输入到程序中的2个坐标x和y。用户输入多边形具有的N边数,并根据N边的数目输入x和y坐标,程序将计算N边的周长
编辑:找到了这个问题的解决方案
意识到索引不应该小于或等于边数。
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
double perimeter(int sides, double* polygon_vert_x,double* polygon_vert_y){
/* Iteration counter. */
int iloopx;
/*variables of type double*/
/*perimeter to store the result of
sqaure root*/
/*dx and dy are used to store values
of x and y co-ordinates calculation*/
double perimeter, dx, dy;
/*initialize perimeter to 0.0*/
perimeter = 0.0;
/* calculate perimeter using loops*/
for(iloopx = 0; iloopx < sides; iloopx++)
{ /*Total length of sides with pythagorean theorem*/
/*distance */
dx = polygon_vert_x[(iloopx+1)%sides] - polygon_vert_x[iloopx];
dy = polygon_vert_y[(iloopx+1)%sides] - polygon_vert_y[iloopx];
/*accumlation*/
perimeter+=sqrt(dx * dx + dy * dy);
}
/*return total value*/
return perimeter;
}
int main(){
double perimet;
int n;
int count =0;
double *polygon_vert_x;
double *polygon_vert_y;
/*input number of side*/
scanf("%d", &n);
/* Allocate Memory of N-size */
polygon_vert_x = malloc(sizeof(double)* n);
polygon_vert_y = malloc(sizeof(double)* n);
/*input x-cords, y-cords*/
for(count=0; count < n; count++)
{
/* Get User Input N-Times */
scanf("%lf %lf", &polygon_vert_x[count], &polygon_vert_y[count]);
}
/* calculate the perimeter of the polygon */
perimet = perimeter(n, polygon_vert_x, polygon_vert_y);
printf("The perimeter length is %.2f units.\n", perimet);
return 0;
}
最佳答案
可以的注意使用%
环绕。这样,您就不必分别处理第一和最后一点。
#include <stdio.h>
#include <stdlib.h>
#include <math.h>
enum {x, y};
double perimeter(int side, double* polygon_vert_x,double* polygon_vert_y);
double side(double *p1, double *p2);
int main(){
double perimet;
int n;
int count =0;
double *polygon_vert_x;
double *polygon_vert_y;
/*input number of side*/
scanf("%d", &n);
/* Allocate Memory of N-size */
polygon_vert_x = malloc(sizeof(double)* n);
polygon_vert_y = malloc(sizeof(double)* n);
/*input x-cords, y-cords*/
for(count=0; count < n; count++)
{
// printf("%d",count);
/* Get User Input N-Times */
scanf("%lf %lf", &polygon_vert_x[count], &polygon_vert_y[count]);
}
/* calculate the perimeter of the polygon */
perimet = perimeter(n, polygon_vert_x, polygon_vert_y);
printf("The perimeter length is %.2f units.\n", perimet);
return 0;
}
double perimeter(int sides, double* polygon_vert_x,double* polygon_vert_y){
double perimeter;
perimeter = 0.0;
int i;
for(i = 0; i < sides; i++)
{
double p[2] = {0.0,0.0};
p[x] = polygon_vert_x[i];
p[y] = polygon_vert_y[i];
double p1[2] = {0.0,0.0};
p1[x] = polygon_vert_x[(i+1)%sides];
p1[y] = polygon_vert_y[(i+1)%sides];
perimeter+=side(p,p1);
}
/*return total value*/
return perimeter;
}
/* calculate length of side */
double side(double *p1, double *p2)
{
double s1, s2, s3;
s1 = (p1[x] - p2[x]);
s2 = (p1[y] - p2[y]);
s3 = (s1 * s1) + (s2 * s2);
return sqrt(s3);
}