java求三角形面积
1.构造一个多形式接受参数的三角形类Triangle,包含有三个边长和求面积的方法,面积值须四舍五入精确到小数点后两位。接收参数的方式:无参数时默认为勾三股四弦五的直角三...
1. 构造一个多形式接受参数的三角形类Triangle,包含有三个边长和求面积的方法,面积值须四舍五入精确到小数点后两位。接收参数的方式:无参数时默认为勾三股四弦五的直角三角形,一个参数时默认为边长为该数值的等边三角形,三个参数时分别为三条边长。将程序文件保存为Tri.java。
class Triangle{
}
//下面Tri类是对Triangle类的测试
class Tri{
public static void main(String[] aa){
System.out.println(new Triangle().getS());
System.out.println(new Triangle(5).getS());
System.out.println(new Triangle(5,8,6).getS());
System.out.println(newTriangle(2,9,6).getS());
}
} 展开
class Triangle{
}
//下面Tri类是对Triangle类的测试
class Tri{
public static void main(String[] aa){
System.out.println(new Triangle().getS());
System.out.println(new Triangle(5).getS());
System.out.println(new Triangle(5,8,6).getS());
System.out.println(newTriangle(2,9,6).getS());
}
} 展开
展开全部
import java.math.BigDecimal;
public class Triangle {
int a,b,c ;//三条边
double S;//面积
boolean isTri = true;
Triangle(){
a=3; b=4; c=5;
}
Triangle(int bian){
a=b=c=bian;
}
Triangle(int bian1,int bian2,int bian3){
if(bian1 + bian2 > bian3 && bian1 + bian3 > bian2 && bian2 + bian3 > bian1){
a = bian1;b=bian2;c=bian3;
}else{
isTri = false;
System.out.print("不是三角形");
}
}
private double getS(){
if(isTri){
int s = (a+b+c)/2;
double ss = Math.sqrt(s * (s - a) * (s - b) * (s - c));
BigDecimal b = new BigDecimal(ss);
return b.setScale(2, BigDecimal.ROUND_HALF_UP).doubleValue();
}
return 0;
}
public static void main(String[] aa){
System.out.println(new Triangle().getS());
System.out.println(new Triangle(5).getS());
System.out.println(new Triangle(5,8,6).getS());
System.out.println(new Triangle(2,9,6).getS());
}
}
展开全部
import java.text.DecimalFormat;
import java.util.Arrays;
public class Triangle {
private double side1;
private double side2;
private double side3;
public Triangle() {
this.side1 = 3;
this.side2 = 4;
this.side3 = 5;
}
public Triangle(double length) {
this.side1 = length;
this.side2 = length;
this.side3 = length;
}
public Triangle(double length1, double length2, double length3) {
this.side1 = length1;
this.side2 = length2;
this.side3 = length3;
}
// 计算三角形面积
public String getS() {
if (isTriangle(side1, side2, side3)) {
double m = ((double) (side1 + side2 + side3)) / 2;
double s = Math.sqrt(m * (m - side1) * (m - side2) * (m - side3));
DecimalFormat df = new DecimalFormat("#.00");
return df.format(s);
} else {
return "不能够构成三角形";
}
}
// 判断是否能构成三角形
public boolean isTriangle(double length1, double length2, double length3) {
double[] nums = { length1, length2, length3 };
Arrays.sort(nums);
if (nums[0] + nums[1] <= nums[2]) {
return false;
}
return true;
}
public static void main(String[] args) {
// System.out.println(new Triangle().getS());
System.out.println(new Triangle(5).getS());
// System.out.println(new Triangle(5,8,6).getS());
//System.out.println(new Triangle(2, 9, 6).getS());
}
}
本回答被网友采纳
已赞过
已踩过<
评论
收起
你对这个回答的评价是?
推荐律师服务:
若未解决您的问题,请您详细描述您的问题,通过百度律临进行免费专业咨询