227k views
2 votes
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 10 miles, 50 miles, and 400 miles. Output each floating-point value with two digits after the decimal point, which can be achieved as follows: printf("%0.2of", your Value);

User BaDr Amer
by
5.5k points

2 Answers

2 votes

Answer:

def driving_cost(driven_miles, miles_per_gallon, dollars_per_gallon):

gallon_used = driven_miles / miles_per_gallon

cost = gallon_used * dollars_per_gallon

return cost

miles_per_gallon = float(input(""))

dollars_per_gallon = float(input(""))

cost1 = driving_cost(10, miles_per_gallon, dollars_per_gallon)

cost2 = driving_cost(50, miles_per_gallon, dollars_per_gallon)

cost3 = driving_cost(400, miles_per_gallon, dollars_per_gallon)

print("%.2f" % cost1)

print("%.2f" % cost2)

print("%.2f" % cost3)

Step-by-step explanation:

User Kthompso
by
5.9k points
7 votes

Answer:

The C program is given below.

#include<stdio.h>

int main() {

double speed, gas_cost, cost_1, cost_10, cost_50, cost_400;

printf("Enter car's speed in miles/gallon ");

scanf("%lf", &speed);

printf("Enter cost of gas in dollars/gallon ");

scanf("%lf", &gas_cost);

// fraction gives the gallons of gas needed for 1 mile.

// gallons of gas needed for 1 mile * cost of 1 gallon of gas = gas cost for 1 mile

cost_1 = (1/speed)*gas_cost ;

// cost of gas for 10 miles

cost_10 = cost_1 * 10;

printf("Cost of gas for 10 miles in dollars is ");

printf( "%0.2f", cost_10 );

printf("\\");

// cost of gas for 50 miles

cost_50 = cost_1 * 50;

printf("Cost of gas for 50 in dollars miles is ");

printf( "%0.2f", cost_50 );

printf("\\");

// cost of gas for 400 miles

cost_400 = cost_1 * 400;

printf("Cost of gas for 400 in dollars miles is ");

printf( "%0.2f", cost_400 );

printf("\\");

return 0;

}

OUTPUT

Enter car's speed in miles/gallon 20

Enter cost of gas in dollars/gallon 30

Cost of gas for 10 miles in dollars is 15.00

Cost of gas for 50 in dollars miles is 75.00

Cost of gas for 400 in dollars miles is 600.00

Step-by-step explanation:

This program takes user input for cost of gas in dollars and speed of the car in miles per gallon.

Next, gallons needed for 1 mile is calculated.

cost_1 = (1/speed)*gas_cost ;

Following this, gallons needed for 10 miles, 50 miles and 400 miles are calculated.

cost_10 = cost_1 * 10;

cost_50 = cost_1 * 50;

cost_400 = cost_1 * 400;

These values are displayed on the screen with two decimal places by using printf( "%0.2f", your_value).

All the variables needed in this program are declared as double.

All the instructions mentioned have been implemented. This program can be tested for all possible positive numbers.

User Gerard G
by
6.1k points