Blank1268
Blank1268

Reputation: 123

My division statement keeps coming out to 0

I am trying to make a program to calculate mpg on a road trip. I have it all laid out but on every run I get 0.0 for my mpg. I could use some help. I had to make mpg and totalMpg floats so I could do floating point division, if that doesn't make sense say so.

package Gas;

import java.util.Scanner;
import static java.lang.System.out;

public class GasTest {

public static void main(String[] args) {

    int gas;
    int miles;
    int trips;
    float mpg;
    float totalMpg = 0;
    int tripCounter = 1;

    Scanner input = new Scanner (System.in);

    out.println("Please input number of trips");
    trips = input.nextInt();

    while (tripCounter <= trips){
        out.println ("Input gallons of gas used");
        gas = input.nextInt();
        out.println("Input miles traveled on trip");
        miles = input.nextInt();
        mpg = (gas / miles) ;
        out.println("Your MPG for this trip was " + mpg);
        totalMpg = (mpg + totalMpg) / 2;
        out.println("Your overall MPG for all trips is " + totalMpg);
        tripCounter++;
    }


}

}

Upvotes: 1

Views: 300

Answers (2)

AllTooSir
AllTooSir

Reputation: 49372

Cast gas to float in the below expression , if you don't want to declare gas as float. This way you can take advantage of Widening Primitive Conversion, as mentioned in JLS.

mpg = ((float)gas / miles) ;

Upvotes: 2

Denys S&#233;guret
Denys S&#233;guret

Reputation: 382140

If miles is greater than gas, as both of them are int, the result will be 0, which will be stored as 0.0 when assigned to the float variable mpg.

You probably should declare them as float or cast gas when computing :

mpg = ((float)gas) / miles ;

Upvotes: 2

Related Questions