C++ 中的等形


对于这个问题,我们给出了多边形的坐标。我们的任务是创建一个程序,以检查给定的多边形是否等形。

等形的形状是指其周长等于其面积的形状。

我们来举一个例子来理解这个问题:

输入:polygon[][] = {{0, 0}, {5, 7}, {2, 0}}

输出:不等形

解释: 

周长 = 18.21
面积 = 7

求解方法

该问题的解决方法在于找出该形状的面积和周长,然后再对它们进行比较,以检查给定的形状是否是等形。

使用坐标来计算周长很简单。我们只需使用坐标找到长度即可找出周长:

周长 = side1 + side2 + side3 

使用以下公式计算面积:

面积 = 1/2 {(x_1 y_2+ x_2 y_3  + ....x_(n-1) y_n  + x_n y_1 )  - (x_2 y_1  + x_3 y_2  + ....+ x_n y_(n-1)  + x_1 n)}  

说明我们解决方案工作原理的程序

示例

实时演示

#include <bits/stdc++.h>
using namespace std;

double findShapeArea(double cord[][2], int n)
{
   double area = 0.0;
   int j = n - 1;
   for (int i = 0; i < n; i++) {
      area += (float)(cord[j][0] + cord[i][0]) * (cord[j][1] - cord[i][1]);
      j = i;
   }

   return abs(area / 2.0);
}

double findShapeperimeter(double cord[][2], int n) {
   
   double perimeter = 0.0;
   int j = n - 1;
   for (int i = 0; i < n; i++) {
      perimeter += sqrt((cord[j][0] - cord[i][0]) * (cord[j][0] - cord[i][0]) + (cord[j][1] - cord[i][1]) * (cord[j][1] - cord[i][1]));
      j = i;
   }
   return perimeter;
}

int isEquableShape(double cord[][2], int n)
{
   int area = findShapeArea(cord, n);
   int peri = findShapeperimeter(cord, n);
   cout<<"The area of the given shape is "<<area<<endl;
   cout<<"The perimeter of the given shape is "<<peri<<endl;
   if (area == peri)
      return 1;
   else
      return 0;
}

int main() {
   
   int n = 3;
   double cord[n][2] = {{0, 0} , {5, 7}, {2, 0}};
   if (isEquableShape(cord, n))
      cout<<"The given shape is an equable shape";
   else
      cout<<"The given shape is not an equable shape";
   return 0;
}

输出 -

The area of the given shape is 7
The perimeter of the given shape is 18
The given shape is not an equable shape

更新于:2021 年 1 月 22 日

128 次浏览

开启您的 职业生涯

完成课程获得认证

开始
广告
© . All rights reserved.