首页  >  文章  >  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删除