Java 如何判断给定边长的三角形是否合法
如我们所知,三角形是一个有三条边的多边形。它由三条边和三个顶点组成。三个内角的和为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
方法2:通过使用用户定义
在这种方法中,三角形的边长值将在程序中被初始化。然后通过将这些边作为参数传递调用一个用户定义的方法,并且在方法内部使用算法来检查给定的三个边是否构成一个有效的三角形。
示例
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中检查给定三边的三角形是否合法。