Java 中如何根据给定边长判断三角形是否有效?


众所周知,三角形是一种具有 3 条边的多边形。它由三条边和三个顶点组成。三个内角之和为 180 度。

在一个有效的三角形中,如果将任意两条边相加,则其和将大于第三条边。根据我们的问题陈述,我们必须使用 Java 编程语言检查如果给出三条边,则三角形是否有效。

因此,我们必须检查以下三个条件是否满足。如果满足,则三角形有效,否则三角形无效。

假设 a、b 和 c 是三角形的三条边。

a + b > c
b + c > a
c + a > b

举几个例子

示例 1

如果边长为 a=8,b=9,c=5

然后使用上述逻辑,

a+b=8+9=17 which is greater than c i.e. 5
b+c=9+5=14 which is greater than a i.e. 8
c+a=5+8=13 which is greater than b i.e. 9

因此,给定边长的三角形有效。

示例 2

如果边长为 a=7,b=8,c=4

然后使用上述逻辑,

a+b=7+8=15 which is greater than c i.e. 4
b+c=8+4=12 which is greater than a i.e. 7
c+a=4+7=11 which is greater than b i.e. 8

因此,给定边长的三角形有效。

示例 3

如果边长为 a=1,b=4,c=7

然后使用上述逻辑,

a+b=1+4=5 which is not greater than c i.e. 7
b+c=4+7=11 which is greater than a i.e. 1
c+a=7+1=8 which is greater than b i.e. 4

因此,给定边长的三角形无效。因为条件 a+b>c 不成立。

算法

  • 步骤 1 - 通过初始化或用户输入获取三角形的边长。

  • 步骤 2 - 检查它是否满足成为有效三角形的条件。

  • 步骤 3 - 如果满足,则打印三角形有效,否则无效。

多种方法

我们提供了不同方法的解决方案。

  • 使用静态输入值

  • 使用用户定义方法

让我们逐一查看程序及其输出。

方法 1:使用用户输入值

在这种方法中,三角形的边长值将在程序中初始化,然后使用算法,我们可以根据给定的三条边检查三角形是否有效。

示例

public class Main { //main method public static void main(String args[]) { //Declared the side length values of traingle double a = 4; double b = 6; double c = 8; //checking if triangle is valid or not by using the logic if((a + b > c || a + c > b || b + c > a)){ System.out.println("Triangle is Valid"); } else { System.out.println("Triangle is not Valid"); } } }

输出

Triangle is Valid

方法 3:使用用户定义

在这种方法中,三角形的边长值将在程序中初始化。然后通过将这些边作为参数调用用户定义的方法,并在方法内部使用算法,我们可以根据给定的三条边检查三角形是否有效。

示例

import java.util.*; import java.io.*; public class Main { //main method public static void main(String args[]){ //Declared the side lengths double a = 5; double b = 9; double c = 3; //calling a user defined method to check if triangle is valid or not checkTraingle(a,b,c); } //method to check triangle is valid or not public static void checkTraingle(double a,double b, double c){ //checking if triangle is valid or not by using the logic if((a + b > c || a + c > b || b + c > a)){ System.out.println("Triangle is Valid"); } else { System.out.println("Triangle is not Valid"); } } }

输出

Triangle is Valid

在本文中,我们探讨了如何使用不同的方法在 Java 中检查如果给出三条边,则三角形是否有效。

更新于: 2022 年 10 月 27 日

8K+ 次查看

开启你的 职业生涯

通过完成课程获得认证

开始学习
广告
© . All rights reserved.