TransWikia.com

Rounding does not match all expected results

Stack Overflow Asked by AA-44 on January 11, 2021

Everything is fine with this program, it matches all the expected outputs required by my instructor except when the input is 66 and 5000
Knowing that the inputs tested were 89 , 1024 which both matched right
but when I input 66 and 5000 I always end up one gallon short ///

import java.util.Scanner;
import java.lang.Math;

public class CostEstimator {
public static void main(String[] args) {
Scanner scnr = new Scanner(System.in);

double distance = 0.0;
double fuelNeeded = 0.0;
double gallonsFuel = 0;
double costNeeded = 0.0;

final double MILES_PER_LITER = 13.7;
final double LITER_PER_GALLON = 3.785;
final double COST_PER_GALLON = 2.629;
    
System.out.println("Enter the distance to be covered (miles):");
distance = scnr.nextDouble();

fuelNeeded = distance/13.7 ;                 
System.out.println("Fuel Needed: " + fuelNeeded + " liter(s)" );  
 
 gallonsFuel = Math.round(fuelNeeded/3.785)  ;
 System.out.println("Gallons needed: " + (int)gallonsFuel + " gallon(s)");

 costNeeded = gallonsFuel * 2.629;
 System.out.println("Cost needed: " + costNeeded + " $" );

}
}

The expected outputs for each input are such

Input 66

Enter the distance to be covered (miles):
Fuel Needed: 4.817518248175182 liter(s)
Gallons needed: 2 gallon(s)
Cost needed: 5.258 $

Input 89

Enter the distance to be covered (miles):
Fuel Needed: 6.496350364963504 liter(s)
Gallons needed: 2 gallon(s)
Cost needed: 5.258 $


Input 5000

Enter the distance to be covered (miles):
Fuel Needed: 364.9635036496351 liter(s)
Gallons needed: 97 gallon(s)
Cost needed: 255.013 $

Input 1024

Enter the distance to be covered (miles):
Fuel Needed: 74.74452554744526 liter(s)
Gallons needed: 20 gallon(s)
Cost needed: 52.58 $

One Answer

The round function rounds to the nearest integer, but when buying fuel for a journey you'd probably want to round up. Double-check what the question requires, whether rounding to the nearest integer or the next higher integer?

Rounding up is called "ceiling" in maths and Math.ceil in Java.

Correct answer by sabik on January 11, 2021

Add your own answers!

Ask a Question

Get help from others!

© 2024 TransWikia.com. All rights reserved. Sites we Love: PCI Database, UKBizDB, Menu Kuliner, Sharing RPP