给定一个长矩形和广度 .任务是找到可以内切的最大三角形的面积。
例子:
Input: L = 5, B = 4
Output: 10
Input: L = 3, B = 2
Output: 3
从图中可以清楚地看出,矩形内可以内切的最大三角形,应该在同一个底上,并且在矩形的相同平行边之间具有升高的高度。
所以,三角形的底= B
三角形的高度 = L
因此面积,
A = (L*B)/2
注意:还应该清楚的是,如果三角形的底边 = 矩形的对角线,仍然如此获得的三角形面积 = lb/2作为矩形的对角线将其分成 2 个等面积的三角形。
下面是上述方法的实现:
C++
// C++ Program to find the biggest triangle
// which can be inscribed within the rectangle
#include
using namespace std;
// Function to find the area
// of the triangle
float trianglearea(float l, float b)
{
// a and b cannot be negative
if (l < 0 || b < 0)
return -1;
// area of the triangle
float area = (l * b) / 2;
return area;
}
// Driver code
int main()
{
float l = 5, b = 4;
cout << trianglearea(l, b) << endl;
return 0;
}
Java
// Java Program to find the biggest triangle
// which can be inscribed within the rectangle
import java.util.*;
class GFG
{
// Function to find the area
// of the triangle
static float trianglearea(float l, float b)
{
// a and b cannot be negative
if (l < 0 || b < 0)
return -1;
// area of the triangle
float area = (l * b) / 2;
return area;
}
// Driver code
public static void main(String args[])
{
float l = 5, b = 4;
System.out.println(trianglearea(l, b));
}
}
Python3
# Python3 Program to find the
# biggest triangle which can be
# inscribed within the rectangle
# Function to find the area
# of the triangle
def trianglearea(l, b) :
# a and b cannot be negative
if (l < 0 or b < 0) :
return -1
# area of the triangle
area = (l * b) / 2
return area
# Driver code
l = 5
b = 4
print(trianglearea(l, b))
# This code is contributed
# by Yatin Gupta
C#
// C# Program to find the biggest
// triangle which can be inscribed
// within the rectangle
using System;
class GFG
{
// Function to find the area
// of the triangle
static float trianglearea(float l,
float b)
{
// a and b cannot be negative
if (l < 0 || b < 0)
return -1;
// area of the triangle
float area = (l * b) / 2;
return area;
}
// Driver code
public static void Main()
{
float l = 5, b = 4;
Console.WriteLine(trianglearea(l, b));
}
}
// This code is contributed
// by inder_verma
PHP
Javascript
输出:
10
如果您希望与专家一起参加现场课程,请参阅DSA 现场工作专业课程和学生竞争性编程现场课程。