C# 程序来计算三角形的面积(Program to find area of a triangle)

给定一个三角形的边,任务是求出该三角形的面积。

例如:

**输入:**a = 5, b = 7, c = 8

**输出:**三角形面积为 17.320508

**输入:**a = 3, b = 4, c = 5

**输出:**三角形面积为 6.000000

**方法:**可以使用以下公式简单地计算 三角形的面积。

其中 a、b 和 c 是三角形边长,

s = (a+b+c)/2

下面是上述方法的实现:

// C# program to print

// Floyd's triangle

using System;

class Test {

// Function to find area

static float findArea(float a, float b,

float c)

{

// Length of sides must be positive

// and sum of any two sides

// must be smaller than third side.

if (a < 0 || b < 0 || c <0 ||

(a + b <= c) || a + c <=b ||

b + c <=a)

{

Console.Write("Not a valid triangle");

System.Environment.Exit(0);

}

float s = (a + b + c) / 2;

return (float)Math.Sqrt(s * (s - a) *

(s - b) * (s - c));

}

// Driver code

public static void Main()

{

float a = 3.0f;

float b = 4.0f;

float c = 5.0f;

Console.Write("Area is " + findArea(a, b, c));

}

}

// This code is contributed Nitin Mittal.

输出

面积为 6

时间复杂度: O(log 2 n)

辅助空间: O(1),因为没有占用额外空间。

给定一个三角形顶点的坐标,任务是找到该三角形的面积。

**方法:**如果给定三个角的坐标,我们可以对下面的区域 应用鞋带公式。

// C# program to evaluate area of

// a polygon usingshoelace formula

using System;

class GFG {

// (X[i], Y[i]) are coordinates

// of i'th point.

static double polygonArea(double []X,

double []Y, int n)

{

// Initialize area

double area = 0.0;

// Calculate value of shoelace

// formula

int j = n - 1;

for (int i = 0; i < n; i++)

{

area += (X[j] + X[i]) *

(Y[j] - Y[i]);

// j is previous vertex to i

j = i;

}

// Return absolute value

return Math.Abs(area / 2.0);

}

// Driver program

public static void Main ()

{

double []X = {0, 2, 4};

double []Y = {1, 3, 7};

int n = X.Length;

Console.WriteLine(

polygonArea(X, Y, n));

}

}

// This code is contributed by anuj_67.

输出

2

时间复杂度: O(n)

辅助空间: O(1)

相关推荐
LongtengGensSupreme9 分钟前
C# 中监听 IPv6 回环地址(Loopback Address)----socket和tcp
c#·ipv6 回环地址
We་ct13 分钟前
LeetCode 42. 接雨水:双指针解法深度剖析与全方法汇总
前端·算法·leetcode·typescript
就是有点傻19 分钟前
C#中如何和西门子通信
开发语言·c#
海底星光22 分钟前
c#进阶疗法 -jwt+授权
c#
液态不合群22 分钟前
如何提升 C# 应用中的性能
开发语言·算法·c#
诗远Yolanda23 分钟前
EI国际会议-通信技术、电子学与信号处理(CTESP 2026)
图像处理·人工智能·算法·计算机视觉·机器人·信息与通信·信号处理
程序员-King.28 分钟前
day165—递归—最长回文子序列(LeetCode-516)
算法·leetcode·深度优先·递归
BHXDML32 分钟前
推导神经网络前向后向传播算法的优化迭代公式
神经网络·算法·机器学习
2401_8414956433 分钟前
【LeetCode刷题】删除链表的倒数第N个结点
数据结构·python·算法·leetcode·链表·遍历·双指针
叫我:松哥43 分钟前
基于YOLO深度学习算法的人群密集监测与统计分析预警系统,实现人群密集度的实时监测、智能分析和预警功能,支持图片和视频流两种输入方式
人工智能·深度学习·算法·yolo·机器学习·数据分析·flask