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 {

// (Xi, Yi) 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 += (Xj + Xi) *

(Yj - Yi);

// 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)

相关推荐
吴可可1231 分钟前
控制弦高精度的样条离散化方法
算法
wuweijianlove41 分钟前
算法设计中的空间复用与数据对齐优化的技术5
算法
yuan199971 小时前
基于 MATLAB PSO 工具箱的函数寻优算法
开发语言·算法·matlab
YUANQIANG20241 小时前
博弈论中势函数与势博弈构造:为什么看似 “先射箭后画靶”
算法·信息与通信
WBluuue1 小时前
Codeforces 1096 Div3(ABCDEFGH)
c++·算法
JaydenAI2 小时前
[MAF预定义ChatClient中间件-06]利用ImageGeneratingChatClient开发专业图片生成Agent
ai·c#·agent·agent管道·chatclient中间件·chatclient管道
wanzehongsheng2 小时前
基于天文算法的双轴太阳能追踪系统:从原理到工程实现
算法
basketball6162 小时前
Kadane算法 C++实现
java·c++·算法
handler012 小时前
【C++】二叉搜索树详解及其模拟实现(代码)
开发语言·c++·算法·c··二叉搜索树·搜索树
luj_17682 小时前
残熵算法的稳健防灾逻辑
c语言·开发语言·c++·经验分享·算法