昨天看到了那个三角形求最大面积的问题,回去证明了半天也没完成
有人可以用java实现吗?
这个算法怎么设计呢?
------解决方案--------------------
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);
}
}
有些小问题,你自己可以改一下