所以我做了一个三角形程序,用户输入3个边。收到这三个值后,您的程序应为以下每个问题提供答案:
我唯一坚持的是它所说的部分,如果你的程序已经确定三角形是等边的,那么就不应该说它是等腰。所以如果我输入2,2,2这样的东西,我需要一些帮助来弄清楚如何解决这个问题。
这是我的代码:
import java.util.*;
public class Triangle {
public static void main(String[] args) {
Scanner keyboard = new Scanner(System.in);
System.out.println("Welcome to the Triangle Program");
System.out.println();
double side1, side2, side3;
System.out.println("Please enter the length of side 1:");
side1 = keyboard.nextDouble();
System.out.println("Please enter the length of side 2:");
side2 = keyboard.nextDouble();
System.out.println("Please enter the length of side 3:");
side3 = keyboard.nextDouble();
keyboard.nextLine();
System.out.println("My analysis of this triangle is");
System.out.println();
if((side1 > side2+side3) || (side2 > side1+side3) || (side3 > side1+side2))
{
System.out.println("This is not a triangle");
System.exit(0);
}
else
{
System.out.println("This is a triangle");
}
if((side1*side1 == (side3*side3)+(side2*side2)) || (side2*side2 == (side3*side3)+(side1*side1)) || (side3*side3 == (side1*side1)+(side2*side2)))
{
System.out.println("This is a right triangle");
}
else
{
System.out.println("This is not a right triangle");
}
if((side1 == side2) && (side2 == side3))
{
System.out.println("This is an equilateral triangle");
}
else
{
System.out.println("This is not an equilateral triangle");
}
if((side1 == side2) || (side2 == side3) || (side3 == side1))
{
System.out.println("This is an isosceles triangle");
}
else
{
System.out.println("This is not an isosceles triangle");
}
double p = (side1 + side2 + side3)/2.0;
double area = Math.sqrt(p * (p - side1) * (p - side2) * (p - side3));
double perimeter = side1 + side2 + side3;
System.out.printf("The area of the triangle is " + "%.3f",area);
System.out.println();
System.out.println("The perimeter of the triangle is " + perimeter);
}
}
答案 0 :(得分:0)
你可以将等边度检查添加到isosceles-ness的检查中(当然否定):
((side1 == side2) || (side2 == side3) || (side3 == side1))
&& !((side1 == side2) && (side2 == side3))
虽然,我认为等边三角形不是等腰。
答案 1 :(得分:0)
我不是复杂布尔表达式的忠实粉丝。我认为你应该首先创建一个布尔变量,以存储三角形是否等边:
boolean isEquilateral = false;
当您对等边三角形的测试成功时,将其设置为true。
if((side1 == side2) && (side2 == side3))
{
System.out.println("This is an equilateral triangle");
isEquilateral = true;
}
在检查isosceles-ness之前,请检查布尔变量:
if(!isEquilateral && (side1 == side2) || (side2 == side3) || (side3 == side1))
{
System.out.println("This is an isosceles triangle");
}