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 中檢查如果給出三條邊,則三角形是否有效。
廣告