I just started learning Java and I have been playing around with it. I am trying to make this program return a double value like 1000/3 = 333.33333..... but it returns 333.000 what am I doing wrong in Java. It works in C though :P. Thanks in Advance!
//Exercise : 4.17
//Program that inputs miles driven and gallons of gas
//Program calcualates and displays: miles per gallon and print out sum of miles per gallon/no of trips
//ie. Will use float for all average results
//miles and gallons should be in integers
import java.util.Scanner;//Program will use Scanner class
public class Mileage
{
//Main method that executes the java program
public static void main ( String[] args )
{
//Declaring variables to be used in program
int miles = 0;
int gallons = 0;
double miles_per_gallon = 0;
double miles_per_gallon_trips = 0;
int sum_miles = 0;
int sum_gallons = 0;
//Creating a Scanner object to get input in command window
Scanner input = new Scanner ( System.in );
while (miles != -1 )
{
//Promping User to get input
System.out.print("\nEnter the number of miles (-1 to exit): ");
miles = input.nextInt();
if ( miles != -1){
sum_miles += miles;//Summing up miles to be used to calculate total average
//Prompt User to enter the number of gallons
System.out.print("\nEnter the number of gallons of gas used: ");
gallons = input.nextInt();
sum_gallons += gallons;//Summing up gallons to use to calculate total average
miles_per_gallon = miles / gallons;//Calculate the avarage of miles per gallon
System.out.printf("\nMiles per gallon: %f\n",miles_per_gallon); //Print out the
}
else
miles = -1;
}
if ( miles_per_gallon > 0.0){
miles_per_gallon_trips = (sum_miles / sum_gallons);
System.out.printf("Total miles Per Gallon is %f\n",miles_per_gallon_trips);}
}//end main method
}//end class Mileage