Exercise 3: Write a program that, given the number of kilometers traveled and th
ID: 3545821 • Letter: E
Question
Exercise 3:
Write a program that, given the number of kilometers traveled and the gallons of gasoline consumed, produces the kilometers per gallon and the kilometers per liter. In your program you should define a function for kilometers per gallon, and another function for kilometers per liter. This program should repeat as many times as the user wishes.
1 Liter = 0.264172051 Gallon
1 Gallon = 3.7854118 Liter
Optional: Let your program not case sensitive to the input, which is accepting Y or N regardless of their case (capital or small).
Hint: this can be done using if statement or using a function of the ctype library.
Explanation / Answer
#include<stdio.h>
#include<ctype.h>
double kmpg(float dist, float gas)
{
return dist/gas;
}
double kmpl(float dist, float gas)
{
return (dist*3.7854118)/gas;
}
int main()
{
double dist, gas;
char choice;
while(1)
{
printf("Enter the no.of distance travelled in kilometers : ");
scanf("%lf",&dist);
printf("Enter the quantity of gasoline consumed in gallons : ");
scanf("%lf",&gas);
printf(" Distance covered per gallon of gasoline is %lf km. ",kmpg(dist,gas));
printf("Distance covered per litre of gasoline is %lf km. ",kmpl(dist,gas));
printf(" Do you want to try again? (press Y or N) : ");
scanf("%c",&choice);
if(choice ==' ')
{
scanf("%c",&choice);
}
while(choice!='Y' && choice!='y' && choice!='N' && choice!='n')
{
printf("Incorrect choice. Press Y or N : ");
scanf("%c",&choice);
}
if(choice == 'N' || choice == 'n')
{
break;
}
else
{
printf(" ");
}
}
return 0;
}
The above is the required code for the program.
Related Questions
Navigate
Integrity-first tutoring: explanations and feedback only — we do not complete graded work. Learn more.