I have a problem with my code's formatting. At the end, it's supposed to print out its results. I am using a printf statement, but it returns numbers that aren't as precise as I need them to be. For example, if one number should be 76.83200000000001, it returns as 76.83200. It is also adding unnecessary zeros at the end of numbers, and if a number should be 28.0, it turns into 28.000000. If possible, can we do this without a BigDecimal
variable? Here's my code so far (NOTE: there are spaces in front of some strings, that's because the website I'm submitting to requires that for some reason):
import java.util.Scanner;
public class Population {
public static void main(String[] args) {
Scanner stdin = new Scanner(System.in);
double startingNumber, dailyIncrease, daysWillMultiply, temp, population;
System.out.print("Enter the starting number organisms: ");
startingNumber = stdin.nextDouble();
while(startingNumber < 2) {
System.out.print("Invalid. Must be at least 2. Re-enter: ");
startingNumber = stdin.nextDouble();
}
System.out.print("Enter the daily increase: ");
dailyIncrease = stdin.nextDouble();
while(dailyIncrease < 0) {
System.out.print("Invalid. Enter a non-negative number: ");
dailyIncrease = stdin.nextDouble();
}
System.out.print("Enter the number of days the organisms will multiply: ");
daysWillMultiply = stdin.nextDouble();
while(daysWillMultiply < 1) {
System.out.print("Invalid. Enter 1 or more: ");
daysWillMultiply = stdin.nextDouble();
}
temp = startingNumber * dailyIncrease;
population = startingNumber;
System.out.println("Day\t\tOrganisms");
System.out.println("-----------------------------");
System.out.println("1\t\t" + startingNumber);
for (int x = 2; x <= daysWillMultiply; x++) {
population += temp;
temp = population * dailyIncrease;
System.out.printf(x + "\t\t%f\n", population);
}
}
}