2.27 LAB: Driving costs Driving is expensive. Write a program with a car's miles/gallon and gas dollars/gallon (both doubles) as input, and output the gas cost for 20 miles, 75 miles, and 500 miles. Output each floating-point value with two digits after the decimal point, which can be achieved as follows: System.out.printf("%.2f", yourValue);

Respuesta :

Answer:

Java

//////////////////////////////////////////////////////////////////////////

import java.util.Scanner;

public class MyClass {

   public static void main(String args[]) {

     double miles_gallon, gas_gallon;

     ////////////////////////////////////////////////

     System.out.print("Enter miles per gallon: ");

     Scanner myObj = new Scanner(System.in);

     miles_gallon = myObj.nextDouble();

     

     System.out.print("Enter gas dollars per gallon: ");

     gas_gallon = myObj.nextDouble();

     

     System.out.println();

     ////////////////////////////////////////////////

     double twenty_miles = 20/miles_gallon*gas_gallon;

     System.out.printf("Gas cost for 20 miles: $%.2f%n%n", twenty_miles);

     

     double seventy_five_miles = 75/miles_gallon*gas_gallon;

     System.out.printf("Gas cost for 75 miles: $%.2f%n%n", seventy_five_miles);

     

     double five_hundered_miles = 500/miles_gallon*gas_gallon;

     System.out.printf("Gas cost for 500 miles: $%.2f", five_hundered_miles);

   }

}

The program is a sequential program, and does not require loops and conditions.

The program in Java where comments are used to explain each line is as follows:

import java.util.*;

public class Main{

public static void main(String[] args) {

    //This declares all variables as double

 double mpg, ppg;

 //This creates a scanner object

 Scanner input = new Scanner(System.in);

 //This prompts the user for mileage

 System.out.print("Car's gas mileage (miles/gallon): ");

 //This gets input for the car mileage

 mpg = input.nextDouble();

 //This prompts the user for the gas price

 System.out.print("Enter the gas price (dollars/gallon): ");

 //This gets input for the gas price

 ppg= input.nextDouble();

 //This prints the cost of 20 miles

 System.out.printf("20 miles will cost $%.2f\n", (20 * ppg / mpg));

 //This prints the cost of 75 miles

 System.out.printf("75 miles will cost $%.2f\n", (75 * ppg / mpg));

 //This prints the cost of 500 miles

 System.out.printf("500 miles will cost $%.2f\n", (500 * ppg / mpg));

 

}

}

Read more about similar programs at:

https://brainly.com/question/24133128