Flightless_bird - 8 months ago 32

Java Question

I am working on a program that calculates the maximum area that can be attained for a fenced-in area, when you have only 100 yards of fencing. One of the four sides is defined by an arbitrarily long fence that already exists. The correct answer (the maximum area) is 1250 yards, which I am getting when I rum the program. However, I am also required to print out the width and length dimensions to go along with that value, and I am getting *very* strange numbers for those values (which are supposed to be 25 and 50). Can anybody explain why this is happening, and how might I fix it?

`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.

*/

Ignore the space after the 1250.0 (formatting on stack overflow)

Answer

It makes more sense to set the variables as

```
if (area >= prev_area){
prev_area = area;
fin_l = l;
fin_w = w;
}
```

Source (Stackoverflow)