public class TriangleArea { private static final int line_number = 5; public static void main(String[] args) { int line[] = {3, 4 ,5, 6, 7}; int a, b, c; /* edges*/ int s = 0; double area = 0.0, tempArea = 0.0; int la = 0, lb = 0, lc = 0; /* edges of the largest area */ for(int i = 0; i < line_number; i++){ s += line[i]; } for(int i = 0; i < line_number; i++){ a = line[i]; for(int j = (i + 2) % line_number; j != i; j = (j + 1) % line_number){ b = line[(i + 1) % line_number] + line[j]; c = s - a - b; tempArea = triangleArea(a, b , c); if(tempArea <= 0) System.out.println("edges:" + a + "," + b + "," + c + " cannot construct a triangle"); else System.out.println("edges:" + a + "," + b + "," + c + "; Area:" + tempArea); /* get the largest area */ if( tempArea > area ){ area = tempArea; la = a; lb = b; lc = c; } } } System.out.println("The largest area is " + area + "edges:" + la + "," + lb + "," + lc); } public static double triangleArea(int a, int b, int c) { double s = (a + b + c) / 2; double temp = (s - a) * (s - b) * (s - c); if(temp <= 0) return -1; return Math.sqrt(s * temp); } } 有些小问题,你自己可以改一下
五个线段,长度分别是3\4\5\6\7,把这五个线段组合成一个三角形,比如a=3+4,b=5+6,c=7,abc是三边。求最大面积及其三边的组合方式
a,b+e,c+d是答案
因为周长一定,三边的标准差越小面积越大
{
private static final int line_number = 5;
public static void main(String[] args)
{
int line[] = {3, 4 ,5, 6, 7};
int a, b, c; /* edges*/
int s = 0;
double area = 0.0, tempArea = 0.0;
int la = 0, lb = 0, lc = 0; /* edges of the largest area */
for(int i = 0; i < line_number; i++){
s += line[i];
}
for(int i = 0; i < line_number; i++){
a = line[i];
for(int j = (i + 2) % line_number; j != i; j = (j + 1) % line_number){
b = line[(i + 1) % line_number] + line[j];
c = s - a - b;
tempArea = triangleArea(a, b , c);
if(tempArea <= 0)
System.out.println("edges:" + a + "," + b + "," + c + " cannot construct a triangle");
else
System.out.println("edges:" + a + "," + b + "," + c + "; Area:" + tempArea);
/* get the largest area */
if( tempArea > area ){
area = tempArea;
la = a;
lb = b;
lc = c;
}
}
}
System.out.println("The largest area is " + area + "edges:" + la + "," + lb + "," + lc);
}
public static double triangleArea(int a, int b, int c)
{
double s = (a + b + c) / 2;
double temp = (s - a) * (s - b) * (s - c);
if(temp <= 0)
return -1;
return Math.sqrt(s * temp);
}
}
有些小问题,你自己可以改一下