目录

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)

本文是转载文章,点击查看原文
如有侵权,请联系 xyy@jishuzhan.net 删除
相关推荐
商bol4527 分钟前
习题与正则表达式
数据结构·c++·算法
LAOLONG-C1 小时前
从零到有的游戏开发(visual studio 2022 + easyx.h)
c语言·ide·算法·visual studio
机器鱼2 小时前
MATLAB基于统计特征与指数退化模型的风力发电机高速轴承剩余寿命预测
人工智能·算法·机器学习
明明明h2 小时前
C#网络编程(Socket编程)
开发语言·网络·c#
clock的时钟2 小时前
数据结构(一)KMP+滑动窗口+链表+栈+队列
数据结构·算法·链表
sugar__salt2 小时前
各种排序思路及实现
数据结构·算法·排序算法
Vitalia2 小时前
⭐算法OJ⭐数据流的中位数【最小堆】Find Median from Data Stream
数据结构·c++·算法·最小堆
点我头像干啥3 小时前
机器学习中的聚类分析算法:原理与应用
人工智能·算法·机器学习
仟濹3 小时前
【C/C++】双指针与前缀和
c语言·c++·算法
www_pp_3 小时前
# 决策树与PCA降维在电信客户流失预测中的应用
算法·决策树·机器学习