首頁  >  文章  >  Java  >  如何在Java中檢查三角形的有效性,當給定邊長時?

如何在Java中檢查三角形的有效性,當給定邊長時?

WBOY
WBOY轉載
2023-09-09 22:53:02581瀏覽

如何在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 中給定三個邊的情況下檢查三角形是否有效。

以上是如何在Java中檢查三角形的有效性,當給定邊長時?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文轉載於:tutorialspoint.com。如有侵權,請聯絡admin@php.cn刪除