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)

相关推荐
钢铁男儿2 小时前
C# 方法(栈帧)
开发语言·c#
强盛小灵通专卖员2 小时前
分类分割详细指标说明
人工智能·深度学习·算法·机器学习
IT猿手5 小时前
基于强化学习 Q-learning 算法求解城市场景下无人机三维路径规划研究,提供完整MATLAB代码
神经网络·算法·matlab·人机交互·无人机·强化学习·无人机三维路径规划
码小跳8 小时前
Halcon案例(一):C#联合Halcon识别路由器上的散热孔
图像处理·c#
万能程序员-传康Kk9 小时前
旅游推荐数据分析可视化系统算法
算法·数据分析·旅游
PXM的算法星球9 小时前
【并发编程基石】CAS无锁算法详解:原理、实现与应用场景
算法
ll7788119 小时前
C++学习之路,从0到精通的征途:继承
开发语言·数据结构·c++·学习·算法
烨然若神人~9 小时前
算法第十七天|654. 最大二叉树、617.合并二叉树、700.二叉搜索树中的搜索、98.验证二叉搜索树
算法
爱coding的橙子9 小时前
每日算法刷题Day2 5.10:leetcode数组1道题3种解法,用时40min
算法·leetcode
程序媛小盐10 小时前
贪心算法:最小生成树
算法·贪心算法·图论