三角形分类算法






4.80/5 (2投票s)
一个简单的算法,用于根据其边长确定三角形的类型
引言
三角形根据其元素的相对大小进行分类。
关于边长,三角形可以是
- 不等边三角形(所有边长都不同)
- 等腰三角形(两条边长相等)
- 等边三角形(所有三条边长都相等)
关于角度,三角形可以是
- 锐角三角形(所有角度都是锐角)
- 直角三角形(一个角度是直角)
- 钝角三角形(一个角度是钝角)
注意:
- 三角形的一个性质是,任意两边长度之和大于第三边的长度。
- 有一种特殊的三角形,称为退化三角形,由三点共线形成。它看起来不像一个三角形,而像一条线段。在这种情况下,它的一个边长等于其他两边的和。
在本技巧中,我们将开发一个算法,根据其边长确定三角形的类型。
Using the Code
以下算法使用 Lua 语言和 ZeroBrane Studio IDE 实现。
--[[--
TriangleType
Determines the type of the triangle by the sides and by the angles
Language: Lua
2018, Jose Cintra
josecintra@josecintra.com
--]]--
-- Compare two floats
local function almostEquals(a, b)
threshold = 0.00001
diff = math.abs(a - b) -- Absolute value of difference
return (diff < threshold)
end
-- Determines the type of the triangle by the sides and by the angles
local function triangleType(a,b,c)
local bySide,byAngle = nil
if (a <= (b + c) and b <= (a + c) and c <= (a + b)) then
--Type of the triangle by sides
if ( a == b and b == c ) then
bySide = 1 -- Equilateral
elseif (a == b or b == c or a == c) then
bySide = 2 -- Isosceles
else
bySide = 3 -- Scalene
end
--Type of the triangle by Angle
if almostEquals(a,(b + c)) or almostEquals(b,(a + c)) or almostEquals(c,(a + b)) then
byAngle = 4 -- Degenerate
elseif almostEquals(a^2,(b^2 + c^2)) or almostEquals(b^2,(a^2 + c^2)) or almostEquals(c^2,(a^2 + b^2)) then
byAngle = 1 -- Right
elseif (a^2 > b^2 + c^2) or (b^2 > a^2 + c^2) or (c^2 > a^2 + b^2) then
byAngle = 2 -- Obtuse
else
byAngle = 3 -- Acute
end
end
return bySide,byAngle
end
-- Main routine
local bySideTypes = {"Equilateral","Isosceles","Scalene"}
local byAngleTypes = {"Right","Obtuse","Acute","Degenerate"}
print("Triangle Type\n")
print("Enter the value of A side: ")
local a = tonumber(io.read())
print("Enter the value of B side: ")
local b = tonumber(io.read())
print("Enter the value of C side: ")
local c = tonumber(io.read())
local bySide,byAngle = triangleType(a,b,c)
if (bySide ~= nil) then
print ("The type of the triangle is " .. bySideTypes[bySide] .. "/" .. byAngleTypes[byAngle])
else
print ("These sides do not form a triangle")
end
-- end
关注点
为了理解该算法,应考虑以下几点
- 为了根据其角度获得三角形的类型,我们使用毕达哥拉斯定理,类似于 此处。
- 在 Lua 语言中,一个函数可以返回多个值。
- 对于浮点值的比较,我们使用
almostEquals
函数,可以根据您的需要调整threshold
变量。 - 为了“良好的实践”,我们已将三角形的类型编码到一个数组中。
历史
2018年10月21日 - 初始版本
2018年10月27日 - 添加了“退化三角形”和 almostEquals
函数
参考文献
- https://study.com/academy/lesson/types-of-triangles-their-properties.html
- https://www.youtube.com/watch?v=I2Lt-jU3IJc
最后的话
感谢阅读!
此算法的源代码也在 GitHub 上提供:MathAlgorithms