我正在制作一个程序,计算围栏区域可以达到的最大区域,当你只有100码的围栏时。四个方面中的一个由已经存在的任意长的围栏定义。正确的答案(最大面积)是1250码,这是我在朗读程序时得到的。但是,我还需要打印宽度和长度尺寸以与该值一起使用,并且我得到非常这些值的奇怪数字(应该是25和50)。任何人都可以解释为什么会发生这种情况,我该如何解决?
public class Prog215c{
public static void main (String[] args){
//Initalizing the final dimension variables
double fin_l = 0;
double fin_w = 0;
//Initalizing the area variables
double area = 0;
double prev_area = 0;
double max_area = 0;
//Trying all l values
for (double l = 100; l > 0; l--){
//Calculating the w value from the l value
double w = (100-l) / 2;
//Calculating the area
area = l * w;
if (area >= prev_area){
prev_area = area;
}
else{
max_area = prev_area;
fin_l = l;
fin_w = w;
}
}
//Outprinting the results
System.out.println("With 100 yards of fencing material:");
System.out.println("A rectangle " + fin_w + " X " + fin_l + " yards produces the maximum area of " +
max_area + " square yards.");
}
}
/*Sample Output
With 100 yards of fencing material:
A rectangle 49.5 X 1.0 yards produces the maximum area of 1250.0 square yards.
*/
忽略1250.0之后的空格(堆栈溢出格式化)
答案 0 :(得分:0)
将变量设置为
更有意义 if (area >= prev_area){
prev_area = area;
fin_l = l;
fin_w = w;
}
答案 1 :(得分:0)
改变这个:
if (area >= prev_area){
prev_area = area;
}
else{
max_area = prev_area;
fin_l = l;
fin_w = w;
}
由此:
if (area >= prev_area){
prev_area = area;
fin_l = l;
fin_w = w;
}
else{
max_area = prev_area;
}