0
我使用Malloc來存儲用戶輸入到程序中的2個座標x和y。用戶需要輸入一個多邊形所具有的N面的數量,並根據N面的數量輸入x和y座標,程序將計算N面多邊形的周長。使用malloc的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;
}
據我所知,你的程序不能處理任意數量的邊。現在,爲什麼p3的x和y的索引不同(0和1)而不是兩個都是0?輸入表明x和y同時被讀取,那麼它們不應該對每個點具有相同的索引嗎? – user3813674
perimeter()中的代碼看起來像是從別人的工作中複製的很糟糕。 – Jasen
環路部分在周邊嘗試,但它不起作用 目前正在處理另一個解決方案,看看我是否可以採取更多的值 –