我得到正确的最终值,但数字错误
I am getting the correct end value, but with the wrong numbers
我正在开发一个程序,计算当您只有 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 后的 space(栈溢出格式化)
将变量设置为
更有意义
if (area >= prev_area){
prev_area = area;
fin_l = l;
fin_w = w;
}
改变这个:
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;
}
我正在开发一个程序,计算当您只有 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 后的 space(栈溢出格式化)
将变量设置为
更有意义 if (area >= prev_area){
prev_area = area;
fin_l = l;
fin_w = w;
}
改变这个:
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;
}