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)

相关推荐
alphaTao5 小时前
LeetCode 每日一题 2026/8/24-2026/8/30
python·算法·leetcode
Interview Aid1125 小时前
TikTok OA 四题分享|半小时内 AC,题目基本都是实现题
java·开发语言·算法·面试·职场和发展
CoderIsArt13 小时前
C#中UI 线程与 Dispatcher
开发语言·ui·c#
顶点多余14 小时前
那些在算法中适合巩固的知识点---1
java·前端·算法
罗西的思考16 小时前
【Agentic RL / 强化学习框架】Molt 设计解读
人工智能·算法·机器学习
hahaha601616 小时前
HLS高层次综合设计技巧--C++类和模板
图像处理·人工智能·算法·计算机视觉
多弗朗皮卡丘17 小时前
算法详解4:买卖股票的最佳时机系列(上)
算法
维克兜率天19 小时前
【维克】动量指标家族:RSI、ROC、CCI、Momentum全面解析
python·算法
AI情绪识别开源20 小时前
检信 AI 智能推广平台(代号:JX-Promote)
人工智能·算法·erlang
老当益壮梁奶奶21 小时前
Linux软件编程学习笔记(八):进程间通信详解(1)
linux·c语言·笔记·学习·算法