Overview
Using DrJava, I have calculated the "Estimated corn plants damaged" based on an alien invasion that left a crop circle x diameter in feet (a user input). I made a calculation to determine an acre being that 43560 feet equals 1 acre. For every acre destroyed, 30000 corn plants are destroyed.
The output I am asking for clarification on why my program is getting a slightly different answer than my calculator is "Estimated corn plants damaged."
My output from my Java program when the user inputs 80
Estimated corn plants damaged: 3462
My calculator's and Google's final calculation of the same diameter
Estimated corn plants damaged: 3450
My Worded Solution
I am getting a different output because the dAcres variable is formatted to round to 3 decimal points for the output but the value it uses for the calculation is not rounded. For example, when the user enters 80 as the diameter, the dAcres variable outputs 0.115. However, the dAcre variable uses .11539 in its calculations instead.
Final Question
How do I make it so my calculation uses only 3 decimal places instead of it's default number of decimal places? Example: 0.115 instead of 0.11539?
My Code
import java.util.*;
import java.text.*;
public class Lab2_Problem2
{
public static final double dPI = 3.14159;
public static void main(String[] args )
{
// DECLARATIONS
// Input-capture variables
double dDiameter;
// Expression-result variables
double dArea;
double dAcres;
double dCornPlantsDamaged;
// Other variables
double dRadius;
double dRadiusSquared;
// Instantiations
Scanner cin = new Scanner(System.in);
DecimalFormat dfDiameter = new DecimalFormat("#######");
DecimalFormat dfArea = new DecimalFormat("#######.00");
DecimalFormat dfAcres = new DecimalFormat("##0.000");
DecimalFormat dfCornPlantsDamaged = new DecimalFormat("#####");
// INITIALIZE
// INPUT
System.out.print("Enter crop circle diameter in feet: ");
dDiameter = cin.nextDouble();
// PROCESSING AND CALCULATIONS
dRadius = dDiameter / (double) 2;
dRadiusSquared = dRadius * dRadius;
dArea = dPI * dRadiusSquared;
dAcres = dArea / (double) 43560;
dCornPlantsDamaged = dAcres * (double) 30000;
// OUTPUT
System.out.println("Crop circle diameter: " + dfDiameter.format(dDiameter) + " feet");
System.out.println("Square feet: " + dfArea.format(dArea));
System.out.println("Acres: " + dfAcres.format(dAcres));
System.out.println("Estimated corn plants damaged: " +
dfCornPlantsDamaged.format(dCornPlantsDamaged));
}
}
Q&A
- Why would you want to calculate by 3 decimal places if your calculator wouldn't do it?
- Because I would like the output to match the calculations being made.